|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
最近学习c语言,关于头插法建立单链表我有一些疑问,希望有大佬能够解答一下,感激不尽。
new_node->next=head->next;
head->next=new_node; //(head是空链表的头节点,new_node是新节点,输出的数据是从head->next开始,不会输出head的数据。假设插入3个结点1,2,3,输出是3,2,1,这个程序是正确的)
我想把程序改为(new_node->next=head; head=new_node;),在我的想法中,假设插入1,2,3,从head开始输出,输出应该是3,2,1,100。但是不论插入几个结点,程序只会输出head的数据,就好像insert()函数没有执行一样,我想了很久不明白为什么,希望有大佬帮下我!
下面贴出正确的程序。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
}Lnode,*Linklist;
Linklist creat_head()
{
Linklist head=NULL;
head=(Linklist)malloc(sizeof(Lnode));
if(head==NULL)
{
printf("内存已满");
return NULL;
}
head->next=NULL;
head->data=100;
return head;
}
void insert(Linklist head,int n)
{
int i;
for(i=0;i<n;i++)
{
Linklist new_node=NULL;
new_node=(Linklist)malloc(sizeof(Lnode));
if(new_node==NULL)
{
printf("内存已满");
}
else
{
printf("插入的结点的值:");
scanf("%d",&new_node->data);
new_node->next=head->next;
head->next=new_node;
}
}
}
void shownode(Linklist head)
{
Linklist tem=head->next;
while(tem)
{
printf("%d \n",tem->data);
tem=tem->next;
}
}
int main()
{
int n;
Linklist a;
printf("插入几个结点:");
scanf("%d",&n);
a=creat_head();
insert(a,n);
shownode(a);
return 0;
}
今天有时间,帮你改好了,写注释的地方是改的地方
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct node
- {
- int data;
- struct node *next;
- }Lnode,*Linklist;
- Linklist creat_head()
- {
- Linklist head=NULL;
- head=(Linklist)malloc(sizeof(Lnode));
- if(head==NULL)
- {
- printf("内存已满");
- return NULL;
- }
- head->next=NULL;
- head->data=100;
- return head;
- }
- void insert(Linklist *temp,int n) //修改为接收二级指针
- {
- int i;
- Linklist head = *temp; //temp就是传进来的头
- for(i=0;i<n;i++)
- {
- Linklist new_node=NULL;
- new_node=(Linklist)malloc(sizeof(Lnode));
- if(new_node==NULL)
- {
- printf("内存已满");
- }
- else
- {
- printf("插入的结点的值:");
- scanf("%d",&new_node->data);
- new_node->next=head; //修改1
- head=new_node; //修改2
- }
- }
- *temp = head; //for循环结束后,将head赋值回去
- }
- void shownode(Linklist head)
- {
- Linklist tem=head;
- while(tem)
- {
- printf("%d \n",tem->data);
- tem=tem->next;
- }
- }
- int main()
- {
- int n;
- Linklist a;
- printf("插入几个结点:");
- scanf("%d",&n);
- a=creat_head();
- insert(&a,n); //传入a的地址,使a改变
- shownode(a);
- return 0;
- }
复制代码
|
|