单链表的操作

<span style="font-size:18px;">#include<iostream>
using namespace std;
//节点结构体
typedef struct Node
{
	int data;
	Node *next;
}Node;
//创建单链表
Node *Creatlist()//返回指针值的函数
{
	Node*head,*p,*q;
	int i=0;
	head=(Node*)malloc(sizeof(Node));
	while(1)
	{
		
		int x;
		cout<<"请输入链表的数据"<<endl;
		cin>>x;
		if(x==0)
			break;
	    p=(Node*)malloc(sizeof(Node));
		p->data=x;
		if((++i)==1)
		{
			head->next=p;
		}
		else
		{
			q->next=p;
		}
		q=p;

	}
	q->next=NULL;
	return head;
}
//打印单链表
void print(Node* head)
{
	Node *p;
	if(head->next==NULL)
	{
		cout<<"链表为空"<<endl;
	    return ;
	}
	p=head->next;
	while(p!=NULL)
	{
		cout<<p->data<<endl;
		p=p->next;
	}
}
//测量链表的长度
int length(Node*head)
{
	int len=0;
	Node*p;
	p=head->next;
	while(p!=NULL)
	{
		len++;
		p=p->next;
	}
	return len;
}
//取第i个节点数据
Node *GetNode(Node *h,int pos)
{
	Node *p=h->next;
	while(--pos)//注意此处是--pos而不是pos--
	{
		p=p->next;
	}
	return p;
}
//单链表的插入
Node *InsertNode(Node *h,int pos,int data)
{
    Node *head=h;
	Node *p=h;
	while(pos--)
	{
		p=p->next;
	}
	Node *s=(Node *)malloc(sizeof(Node));
	s->next=p->next;
	p->next=s;
	s->data=data;
	return head;
	
}
//单链表的删除
//pos   节点删除位置
Node *DeleteNode(Node *h,int pos)
{
	Node *head=h;
	Node *p=h;
	while(--pos)
	{
		p=p->next;
	}
	p->next=(p->next)->next;
	return head;
}
//实现单链表的逆置
Node *ReverseNode(Node *h)
{
	Node*p=h->next;
	Node*q=p->next;
	p->next=NULL;
	Node*r;
	while(q!=NULL)
	{
		r=q->next;
		q->next=p;
		p=q;
		q=r;
	}
	h->next=p;
	return h;
}
//寻找链表的中间元素
Node *Search(Node *h)
{
	Node*current=NULL;
	Node*mid=NULL;
	int i=0;
	int j=0;
	current=h->next;
	mid=h->next;
	while(current!=NULL)
	{
		if(i/2>j)
		{
			mid=mid->next;
			j++;
		}
		i++;
		current=current->next;
	}
	return  mid;
}
//判断是否有环
bool IsCircle(Node*h)
{
	Node*p1=h;
	Node*P2=h;
	do
	{
		p1=p1->next;
		p2=p2->next->next;
	}while(p2&&p2->next&&p2!=p1)
		if(p1==p2)
		{
			return true;
		}
		else
		{
			return false;
		}

}
int main()
{
	cout<<"链表操作:"<<endl;
	Node*head;
	//创建数字链表
	head=Creatlist();
	//打印数字链表
	print( head);
	//判断链表是否存在环
	Node*start=head->next->next->next;
	start->next=head->next;
	bool loop;
	loop=IsCircle(head);
	cout<<loop;
	//寻找链表的中间元素
	Node *mid;
	mid= Search(head);
	cout<<mid->data;

	//求数字链表的长度
	int L(0);
    L=length(head);
	cout<<L<<endl;
	//求取某一节点的数据
	Node *p;
	int pos=3;
	p=GetNode(head,pos);
	cout<<p->data<<endl;
	//在第i个节点后插入一个节点
	int i;
	cout<<"插入节点的位置:";
	cin>>i;
	int data;
	cout<<"插入节点的数据:";
	cin>>data;
	head=InsertNode(head, i,data);
	print( head);
	//删除某一个节点
    head=DeleteNode(head,3);
	print(head);
	//反转链表
	head=ReverseNode(head);
	print(head);

	return 0;
}</span>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值