链表的每个节点应由数据和一个结构体指针组成。其中,前一个节点的结构体指针应该指向后一个节点。
创建一个链表:
首先定义一个结构体,其中需要包含一个指向自己的结构体指针;
struct Test
{
int num;
struct Test *next;
};
定义节点,将节点联系起来;
struct Test s1 = {1,NULL};
struct Test s2 = {2,NULL};
struct Test s3 = {3,NULL};
s1.next = &s2;
s2.next = &s3;
遍历一个链表:
void printLink(struct Test *head)
{
struct Test *point;
point = head;
while(1)
{
if(point != NULL)
{
printf("%d ",point->num);
point = point->next;
}
else{
putchar('\n');
break;
}
}
}
计算链表的节点总数:
int findLinkNodeNum(struct Test *head)
{
int cnt = 0;
while(head != NULL){
cnt++;
head = head->next;
}
return cnt;
}
查找链表中有没有这个节点:
int searchLinkNode(struct Test *head,int data)
{
while(head != NULL){
if(head->num == data){
return 1;
}
head = head->next;
}
return 0;
}
在对应节点后面插入一个新的节点:
int insertFromBehind(struct Test *head,int data,struct Test *new)
{
struct Test *p = head;
while(p != NULL){
if(p->num == data){
new->next = p->next;
p->next = new;
return 1;
}
p = p->next;
}
return 0;
}
在对应节点前面插入节点:
注意事项:在节点前面插入节点分为两种情况
第一种是在头结点前面插入,这种情况会改变头结点的位置
第二种情况就是在其他节点前面插入。
代码如下:
struct Test* insertFromFor(struct Test *head,int data,struct Test *new)
{
struct Test *p = head;
if(p->num == data){ //在头结点前面插入
new->next = p;
return new;
}
while(p->next != NULL){ //在其他节点前面插入
if(p->next->num == data){
new->next = p->next;
p->next = new;
return head;
}
p = p->next;
}
return head;
}
还有一个需要注意的点是,在b节点前面插入一个c节点,需要找到b节点前面的a节点,然后先把
c->next = a->next;然后 a->next = c。所以在代码中的循环判断条件与在节点后面插入的循环判断条件有所不同。
删除对应的节点:
逻辑和在节点前面插入节点相似;分为删除头结点和其他节点两种情况。也是需要先找到删除的b节点的前一个a节点,然后令a->next = a-z.next->next;返回头结点。。
文章内若有错误,敬请指出,互相交流,共同进步!