C语言:单链表内节点删除

#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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值