单向链表的头插法和尾插法

#include<stdio.h>
#include<stdlib.h>
typedef int data_t;
typedef struct node{
data_t data;
struct node *next;
}list;


list *list_head()
{
list *q=(list *)malloc(sizeof(list));
q->next=NULL;
return q;


}

int insert_node(list *head,int n)
{
int data,i;
list *q=head;
for(i=0;i<n;i++)
{

scanf("%d",&data);

//这是一种尾插法,首先注意一点,如果没有上面的list *q=head,这里的q->next是没有办法直接用的,因为就算我们定义好了这个指针变量,如果不让这个指针变量指向一块

开辟好的地址空间,会报段错误。先对p指向的这块空间里赋值,先令这块空间里的一个指针指向null。而q此时是一块开辟好的地址空间,令q里面的指针指向p,也就是q指向的节点的下一个节点就是p指向的节点,也就是让q指向的节点与p指向的节点相连接,然后q指向p指向的节点。继续开辟下一块地址空间,上一次开辟好的地址空间指向这次开辟的地址空间,上次开辟的地址空间由q指向,所以q-》next=q。然后继续让q=p。

list *p=(list*)malloc(sizeof(list));
p->data=data;
p->next=NULL;
q->next=p;
q=p;
}
}
int change_node(list *head,int pos,data_t a)
{
int j;
for(j=0;j<=pos;j++)
{
head=head->next;
}
head->data=a;
}


insert_pos_node(list *head,data_t pos,data_t a)
{
int j;
list *p=(list*)malloc(sizeof(list));
for(j=0;j<=pos;j++)
{
head=head->next;
}
p->data=a;
p->next=head->next;
head->next=p;


}


int search_pos_node(list *head,int i)
{
int j;
for(j=0;j<=i;j++)
{
head=head->next;
}
printf("%d\n",head->data);




}


int del_pos_node(list *head,int i)
{
int j;
for(j=0;j<i;j++)
{
head=head->next;
}
head->next=head->next->next;


}
int show_node(list *head,int i)
{
int j;
for (j=0;j<i;j++)


{
head=head->next;


printf("%3d",head->data);
}
putchar(10);
}




int main(int argc, const char *argv[])
{
list *h=list_head();
insert_node(h,5);
printf("the link list is:\n");

show_node(h,5);

改变链表中的数字

printf("change the third number is 0\n");
change_node(h,2,0);
show_node(h,5);
增加链表中的数字
printf("add the second number is 11\n");
insert_pos_node(h,1,11);

show_node(h,6);

查找

printf("the third number is:\n");
search_pos_node(h,2);
删除
printf("deled the second number\n");
del_pos_node(h,2);
show_node(h,5);
return 0;

}

按这种顺序输出的数据是正序的

如果是这种情况

int insert_node(link *head,data_t data)
{
link* node =(link*)malloc(sizeof(link));
    node->data=data;
node->next=head->next;
head->next=node;
}

就是头指针不动,新增加的节点也就是新开辟的地址空间夹在头结点和已有节点之间,所以这种输出的数据就是倒序的。

猜你喜欢

转载自blog.csdn.net/chengchaonan/article/details/79688134