#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct List
{
int number;
int total;
struct List *next;
};
typedef struct List Node;
typedef Node *Link;
int data[2][MAX] = {1, 3, 5, 7, 2, 4, 6, 8, 9, 0, 15, 35, 20, 23, 33, 45, 55, 56, 15, 10};
/*************************
* 删除链表内节点
************************/
Link delete_list(Link head, int key)
{
Link pointer;
Link back;
pointer = head; //pointer节点为首节点
while(1)
{
if(pointer->next == NULL)
{
printf("Not Found!\n");
break;
}
if(head->number == key) //删除首节点
{
head = pointer->next;
free(pointer);
break;
}
back = pointer;
pointer = pointer->next; //往下一个节点
if(pointer->number == key) //在链表的重点或尾端
{
back->next = pointer->next;
free(pointer);
break;
}
}
return head;
}
/************************
* 释放链表
************************/
void free_list(Link head)
{
Link pointer;
while(head != NULL)
{
pointer = head;
head = head->next;
free(pointer);
}
}
/************************
* 打印链表
************************/
void print_list(Link head)
{
Link pointer;
pointer = head;
while(pointer != NULL)
{
printf("[%d, %d]", pointer->number, pointer->total);
pointer = pointer->next;
}
printf("\n");
}
/************************
* 建立链表
***********************/
Link create_list(Link head)
{
Link pointer;
Link new;
int i;
head = (Link)malloc(sizeof(Node));
if(head == NULL)
{
printf("memory allocate failure!\n");
}
else
{
head->number = data[0][0]; //定义首节点编号
head->total = data[1][0];
head->next = NULL;
pointer = head; //pointer定义为首节点
for(i = 1; i < MAX; ++i)
{
new = (Link)malloc(sizeof(Node));
new->number = data[0][i];
new->total = data[1][i];
new->next = NULL;
pointer->next = new; //将新节点串联在原列表尾端
pointer = new; //列表尾端节点为新节点
}
}
return head;
}
int main()
{
Link head;
int key = 0;
head = create_list(head);
if(head != NULL)
{
print_list(head);
while(1)
{
printf("please input the data number for delete: ");
scanf("%d", &key);
if(key == 0) //输入为0结束
break;
head = delete_list(head, key);
print_list(head);
}
free_list(head);
}
}
C语言:单链表内节点删除
最新推荐文章于 2024-06-29 01:13:46 发布