C中手动创建链表细节注意点

#include<stdio.h>
#include<stdlib.h>

typedef struct student                         //定义一个结构体
{
  int score;
  struct student *next;
}linklist;

linklist *creat(int n)
{
	linklist *head, *node, *end;               //定义头节点,普通节点,尾部节点;
	head = (linklist*)malloc(sizeof(linklist));//分配地址
	end = head;                                //若是空链表则头尾节点一样
	for (int i = 0; i < n; i++) 
	{
		node = (linklist*)malloc(sizeof(linklist));
		scanf("%d", &node->score);
		end->next = node;
		end = node;
	}
	end->next = NULL;                            //结束创建
	
    while(head->next)
	{
	 printf("%d->",head->score);
	 head=head->next;
	}
	return head;
}
int main()
{
creat(3);
system("pause");
return 0;
}

1.head是所创建的头指针,本来想通过head,将节点内的数据域依次打印,利用head=head->next将数据域打印出来,输入1,2,3,结果却出现 以下情况:

正常应该显示的是1->2->3,结果是3没有出现,1的前面出现的数据也不正确,这是怎么回事?

解答:其实问题就出现在head身上,head本身就是一个头指针,我们知道,头指针一般数据域是不输入数值的,而head->score,所指的就是head头指针中的数据域,所以第一次打印的就是head中的数据域,最后3没有显示出来,是因为for循环,只循环三次。

正确的解决方式是:定义linklist下的一个指针p,p=head->next,这样p就是head指针所指的下一位结点了。以下附正确代码:

#include<stdio.h>
#include<stdlib.h>

typedef struct student                         //定义一个结构体
{
  int score;
  struct student *next;
}linklist;

linklist *creat(int n)
{
	linklist *head, *node, *end;               //定义头节点,普通节点,尾部节点;
	head = (linklist*)malloc(sizeof(linklist));//分配地址
	end = head;                                //若是空链表则头尾节点一样
	for (int i = 0; i < n; i++) 
	{
		node = (linklist*)malloc(sizeof(linklist));
		scanf("%d", &node->score);
		end->next = node;
		end = node;
	}
	end->next = NULL;                            //结束创建
	linklist *p;
	p=head->next;
    while(p)
	{
	 printf("%d->",p->score);
	 p=p->next;
	}
	return head;
}
int main()
{
creat(3);
system("pause");
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_18671205/article/details/89704402
今日推荐