本文将介绍单向链表的建立,遍历,删除操作。
首先是结构体定义:
#include <stdio.h>
#include <stdlib.h>
typedef struct Integer{
int num;
struct Integer *next;
}Node, *Linklist;
单向链表的创建如下(不带头节点):
Node* create_list(const int n)
{
Linklist head,p1,p2;
head = NULL;
printf("Please input the element\n");
for(int i=0; i<n; ++i){
p1 = (Linklist)malloc(sizeof(Node));
scanf("%d",&p1->num);
if(head == NULL) //Without the lead node
head = p1;
else
p2->next = p1;
p2 = p1;
}
p1->next = NULL;
return head;
}
遍历操作如下:
void print_list(Linklist p)
{
while(p){
printf("%d ",p->num);
p = p->next;
}
printf("\n");
}
下面是删除操作,通过两个节点遍历链表,节点p2负责找到对应元素,然后将p2的前驱结点p1指向p2的后继节点p2->next,相当于删除了p2,并释放p2所占用的内存,防止内存泄漏。
void delete_list(Linklist head, int key)
{
Linklist p1,p2;
p1 = head;
p2 = NULL;
if(p1){
if(p1->num == key){ //If to delete the firest node.
head = head->next;
free(p1);
print_list(head);
}
else{
for(p1=head,p2=p1->next; p2!=NULL,p2->num!=key; p1=p1->next,p2=p2->next); //Using two nodes to traverse the list,until to find the element to be deleted.
if(p2 != 0){
p1->next = p2->next;
free(p2);
print_list(head);
}
}
}
}
主函数部分如下:
int main(int argc, char* argv[])
{
int n,key;
Linklist q = NULL;
printf("Please the number of node you want to create:\n");
scanf("%d",&n);
q = create_list(n);
print_list(q);
printf("Please input the number you want to delete:\n");
scanf("%d",&key);
delete_list(q,key);
return 0;
}
运行结果示例如下: