单链表的建立、求长、插入、删除、输出和释放 (带头结点)

#include<iostream>
using namespace std;

typedef struct node
{
	int data;
	struct node *next;
}Node, *List;

//建立带头结点的单链表
List createList()
{
	Node *head, *p1, *p2;
	p1 = p2 = head = new Node;//头结点

	int num;
	cin >> num;
	while(-1 != num)
	{
		p1 = new Node; 
		p1->data = num;
		p2->next = p1;
		p2 = p1;
		cin >> num;
	}
	p2->next = NULL; //不可少

	return head;
}

int getListLength(List p)
{
	int length = 0;
	while(NULL != p->next)
	{
		length++;
		p = p->next;
	}
	
	return length; //不包括头结点
}

//把element插入到第position个位置
List insertNode(List p, int position, int element)
{
	int length = getListLength(p);
	if(position < 1 || position > length + 1)
	{
		cout << "wrong position" << endl;
		exit(1);
	}

	Node *p1 = p ->next;
	Node *p2 = p;
	int i;
	for(i = 0; i < position - 1; i++)
	{
		p2 = p1;
		p1 = p1->next;
	}

	Node *s = new Node;
	s->data = element;

	p2->next = s;
	s->next = p1;

	return p;
}

List delNode(List p, int num)
{
	Node *p1 = NULL, *p2 = NULL;
	if(NULL == p->next)
		return p;

	p1 = p->next;
	p2 = p; //不可少

	//注意while中条件的顺序
	while(NULL != p1 && num != p1->data)
	{
		p2 = p1;
		p1 = p1->next;
	}

	//注意if中条件的顺序
	if(NULL == p1)
		cout << "not been found" << endl;
	else
	{
		p2->next = p1->next;
		delete p1;
	}

	return p;
}

void printList(List p)
{
	while(NULL != p->next)
	{
		cout << p->next->data << " ";
		p = p->next;
	}
	cout << endl;
}

//下面采用递归释放(也可循环释放)
void releaseList(List p)
{
	if(NULL == p->next)
		delete p;
	else
	{
		releaseList(p->next);
		delete p;
	}
}

int main()
{
	List head = createList();
	printList(head);

	int position = 4;
	int element = 100;

	head = insertNode(head, position, element);
	printList(head);

	int num = 3;
	head = delNode(head, num);
	printList(head);

	releaseList(head);

	return 0;
}



 

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值