题解 | #牛牛的链表添加节点#
牛牛的链表添加节点
http://www.nowcoder.com/practice/e33b79c2e15a41f9b541e73cd256124a
#include <stdio.h>
#include <stdlib.h>
typedef struct list{
int data;
struct list *next;
}list,*linklist;
//链表内容打印
void ptink(list *head)
{
struct list *point=head;
while(point!=NULL)
{
printf("%d ",point->data);
point=point->next;//while里面的判断其实是在判断point->next是否为NULL
}
putchar('\n');
}
#if 1
list *addList(list *head,int x,int n)
{
int i=0;
list *newlist = (list *)malloc(sizeof(list));
newlist->data = x;
newlist->next = NULL;
list *point = head;
for(i=1;;i++)
{
if(x==0) //判断是否在链表头添加
{
newlist->next = point;
head = newlist;
return head;
}
else if(i==n) //判断是否在链表尾添加
{
point->next = newlist;
return head;
}
else if(i==x)
{
newlist->next = point->next ;
point->next = newlist;
return head;
}
point = point->next ;
}
return head;
}
int main()
{
int i,x,n;
scanf("%d %d",&n,&x);
int arr[n];
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
//链表的创建
list *headList = NULL;
list *arrList = NULL;
list *head = NULL;
list *ListAdd = NULL;
head = headList; //防止 headList 不为空链表的时候,而导致下面循环链表无头
//尾插法
for(i=0;i<n;i++)
{
arrList = (list *)malloc(sizeof(list));
arrList->data = arr[i];
arrList->next = NULL; //将headList放在arrList->next,即arrList的数据是放在headList的前面的
//headList=head;
if(headList == NULL)
{
headList = arrList; //
head = headList;
}
else
{
while(headList->next != NULL)
{
headList = headList->next ;
}
headList->next = arrList;
}
}
ListAdd = addList(head,x,n);
ptink(ListAdd);
return 0;
}
#endif
#include <stdlib.h>
typedef struct list{
int data;
struct list *next;
}list,*linklist;
//链表内容打印
void ptink(list *head)
{
struct list *point=head;
while(point!=NULL)
{
printf("%d ",point->data);
point=point->next;//while里面的判断其实是在判断point->next是否为NULL
}
putchar('\n');
}
#if 1
list *addList(list *head,int x,int n)
{
int i=0;
list *newlist = (list *)malloc(sizeof(list));
newlist->data = x;
newlist->next = NULL;
list *point = head;
for(i=1;;i++)
{
if(x==0) //判断是否在链表头添加
{
newlist->next = point;
head = newlist;
return head;
}
else if(i==n) //判断是否在链表尾添加
{
point->next = newlist;
return head;
}
else if(i==x)
{
newlist->next = point->next ;
point->next = newlist;
return head;
}
point = point->next ;
}
return head;
}
int main()
{
int i,x,n;
scanf("%d %d",&n,&x);
int arr[n];
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
//链表的创建
list *headList = NULL;
list *arrList = NULL;
list *head = NULL;
list *ListAdd = NULL;
head = headList; //防止 headList 不为空链表的时候,而导致下面循环链表无头
//尾插法
for(i=0;i<n;i++)
{
arrList = (list *)malloc(sizeof(list));
arrList->data = arr[i];
arrList->next = NULL; //将headList放在arrList->next,即arrList的数据是放在headList的前面的
//headList=head;
if(headList == NULL)
{
headList = arrList; //
head = headList;
}
else
{
while(headList->next != NULL)
{
headList = headList->next ;
}
headList->next = arrList;
}
}
ListAdd = addList(head,x,n);
ptink(ListAdd);
return 0;
}
#endif