链表的遍历、前插入和后插入
概念:链表是一种数据结构,用于存储具有线性关系的数据元素。与数组不同,链表中的元素在内存中的位置不一定是连续的。链表中的每个元素称为节点,每个节点包含两个部分:数据域和指针域。指针域用于指向下一个节点,从而将各个节点连接起来形成链表。
图示
代码示例
#include<stdio.h>
struct Test
{
int date;
struct Test *node;
};
int printlink(struct Test *p)
{
while(p!=NULL)
{
printf("%d ",p->date);
p = p->node;
}
putchar('\n');
}
int insertlink(struct Test *t, struct Test *new ,int data)
{
while(t != NULL)
{
if(t->date == data)
{
new->node = t->node;
t->node = new;
}
t = t->node;
}
}
struct Test* insert_front(struct Test *head, struct Test *new, int data)
{
if(head->date == data)
{
new->node = head;
return new;
}
while(head != NULL)
{
if(head->node->date == data)
{
new->node = head->node;
head->node = new;
}
head = head->node;
}
}
void main()
{
int arry[] = {1,2,3};
struct Test *head = NULL;
for(int i=0;i<(sizeof(arry)/sizeof(arry[0]));i++)
{
printf("%d\n",arry[i]);
}
struct Test t1 = {1,NULL};
struct Test t2 = {2,NULL};
struct Test t3 = {3,NULL};
struct Test t4 = {4,NULL};
struct Test t5 = {5,NULL};
t1.node = &t2;
t2.node = &t3;
t3.node = &t4;
t4.node = &t5;
struct Test t = {33,NULL};
struct Test tt = {33,NULL};
printlink(&t1);
head = insert_front(&t1, &t, 1);
printlink(head);
insertlink(head, &tt,1);
printlink(head);
}