思路:
head指向新结点,新结点的next指向被插入位置。
insert函数:
void insert(int x)
{
st *temp=(st*)malloc(sizeof(st)); //插入的新结点
temp->data=x;//data存要插入的x值
temp->next=NULL;
if(head!=NULL) //链表非空
temp->next=head;
head=temp;
}
最后一件事:
第三句temp->next=NULL;仅当列表为空时才使用,但是我们会发现,链表为空的时候,head就是NULL因此我们可以避免写两个语句,直接合并为:
void insert(int x)
{
st *temp=(st*)malloc(sizeof(st));
temp->data=x;
temp->next=head;
head=temp;
}
完整的代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node* next;
}st;
st *head;
void insert(int x)
{
st *temp=(st*)malloc(sizeof(st));
temp->data=x;
temp->next=head;
head=temp;
}
void print()
{
st* p=head;
printf("the list is:\n");
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
head=NULL;
printf("输入几个数?");
int n;
scanf("%d",&n);
int x;
for(int i=0;i<n;i++)
{
scanf("%d",&x);
insert(x);
print();
}
printf("\n");
return 0;
}
运行: