链表的一系列操作

#include <iostream>
#include <malloc.h>
#include <stdlib.h>
using namespace std;
typedef int ElemType;
typedef struct Node
{
	ElemType data;
	Node* next;
}node,*pNode;
pNode create_list();
void traverse(pNode);
bool remove(pNode,int,int*);
bool insert(pNode,int,int);
bool isempty(pNode head);
int lenthlist(pNode head);
void sortlist(pNode head);
int main()
{
	pNode pHead;
	pHead=create_list();//为方便测试,数据元素初始为1 3 5 7。
	if(isempty(pHead))cout<<"The list is empty."<<endl;
	else cout<<"The list is not empty."<<endl;
	cout<<"The lenth of list is "<<lenthlist(pHead)<<"."<<endl;
	traverse(pHead);

	int val;
	if(!remove(pHead,3,&val))exit(-1);//为方便测试,删除数据元素3,即剩下的元素为1 5 7
	else cout<<"Your delete the num of the list, it is "<<val<<endl;
	traverse(pHead);

	if(!insert(pHead,3,2))exit(-1);//为方便测试,在第三个位置添加元素2,即当前链表的元素为1 5 2 7
	else cout<<"Your add one num to the list, its position is 3, the value is 2."<<endl;
	traverse(pHead);

	sortlist(pHead);
	cout<<"After sorting, the list is"<<endl;//为方便测试,对链表进行排序,排序完链表元素为1 2 5 7
	traverse(pHead);

	return 0;
}
pNode create_list()
{
	pNode head=(node*)malloc(sizeof(node));//生成一个头指针,并使这个头指针指向头结点
	if(head==0)exit(-1);
	int len;pNode tail=head;//生成一个尾指针,初始化值为head
	tail->next=NULL;
	cout<<"Please enter lenth of list"<<endl;
	cin>>len;
	cout<<"Your want to create the list, its lenth is "<<len<<endl;
	if(len<0)exit(-1);
	for(int i=0;i<len;i++)
	{
		pNode New=(pNode)malloc(sizeof(node));
		if(New==0)exit(-1);
		cin>>New->data;
		tail->next=New;
		New->next=NULL;
		tail=New;
	}
	return head;
}
void traverse(pNode head)
{
	if(head->next==0) exit(-1);
	pNode p=head->next;
	int i=1;
	while(p)
	{
		cout<<"The number "<<i<<" of the list is "<<p->data<<endl;
		i++;
		p=p->next;
	}
	cout<<endl<<endl;
}
bool remove(pNode head,int pos,int* val)
{
	pNode p=head;int i=0;
	pNode q=NULL;
	while(p->next!=0&&i<pos-1)
	{
		p=p->next;i++;
	}
	if(p->next==0||i>pos-1)return false;
	q=p->next;
	*val=q->data;
	p->next=q->next;
	free (q);
	return true;
}
bool insert(pNode head,int pos,int val)
{
	pNode p=head;int i=0;
	while(p!=0&&i<pos-1)
	{
		p=p->next;
		i++;
	}
	if(p==0||i>pos-1)return false;
	pNode q=(pNode)malloc(sizeof(node));
	if(q==0)return false;
	q->next=p->next;
	p->next=q;
	q->data=val;
	return true;
}
bool isempty(pNode head)
{
	if(head->next!=0)return false;
	else return true;
}
int lenthlist(pNode head)
{
	int len=0;pNode p=head->next;
	while(p!=0)
	{
		p=p->next;
		len++;
	}
	return len;
}
void sortlist(pNode head)
{
	int len=lenthlist(head);
	pNode p,q;
	for(p=head->next;p!=NULL;p=p->next)
	{
		for(q=p->next;q!=NULL;q=q->next)
		{
			if(p->data>q->data)
			{
				int temp=p->data;
				p->data=q->data;
				q->data=temp;
			}
		}
	}
} 

结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值