C/C++ | 28-20 写出程序删除链表中的所有节点

/*
删除所有链表的节点
*/
#include 
#include 
#include 
#include 
#include   
#include 
#include 
#include 
#include 

using namespace std;

typedef struct LNode
{
	int data;
	struct LNode *next;
}LNode;

LNode *CreatLink(int num)  // 构造
{
	int i=1;
	LNode *head, *tail, *p;
	head = (LNode *)malloc(sizeof(LNode));
	tail = head;
	while (num--)
	{
		p = (LNode *)malloc(sizeof(LNode));
		p->data = i;
		tail->next = p;
		tail = p;
		i++;
	}
	tail->next = NULL;
	return head;
}

LNode *FindLink(LNode *head,int X)  //查找
{
	assert( head != NULL);
	LNode *chick=head->next;
	while (chick != NULL)
	{
		if (chick->data == X)
			return chick;
		else
			chick = chick->next;
	}
	return NULL;
}

void DeleteLink(LNode *head, int X)  //删除
{
	assert(head != NULL);
	LNode *p;
	LNode *q;
	p=FindLink(head, X);
	q = p->next;
	p->data = q->data;
	p->next = q->next;
	free(q);
}

void DeleteAllLink(LNode *head)
{
	assert(head != NULL);
	LNode *p ;
	while (head!=NULL)
	{
		p = head->next;
		free(head);
		head = p;
	}
	cout << "all Linked Deleted!" << endl;  //在这里head已为NULL
}

int main()
{
	LNode *head = CreatLink(50);
	DeleteLink(head, 5);
	DeleteAllLink(head);
	system("pause");//这里head随机给值了
	return 0;
}

你可能感兴趣的:(C/C++ | 28-20 写出程序删除链表中的所有节点)