链表操作之快慢指针

使用包括链表的找环 判断链表相交 找倒数第几个节点。。。。。


代码:


#include<iostream>
#include<assert.h>
using namespace std;


typedef struct node
{
    int data;
	int size;
	struct node*next;
}node;

typedef  node* Lnode;

void init(Lnode &head)
{
	head= new node;
	head->next=NULL;
	head->data=-1;
	head->size=0;
}

Lnode Buynode(int data)
{
	Lnode p=new node;
	p->next=NULL;
	p->data=data;
	return p;
}
void pushback(Lnode head,int data)
{
	assert(head != NULL);
     Lnode cur=head;
	while(cur->next != NULL)
	{
       cur=cur->next;
	}
	 Lnode newnode=Buynode(data);
	 cur->next=newnode;
	 ++head->size;
}

void CreatCircle_Link(Lnode head,int pos)
{
	assert(head != NULL && head->size >1);
	int i=0;
	Lnode cur=head;
    while(i<pos)
	{
      cur=cur->next;
	  ++i;
	}
	Lnode temp=cur;
	while(cur->next != NULL)
	{
		cur=cur->next;
	}
	cur->next=temp;
}
void print(Lnode head)
{
     assert(head != NULL);
	 Lnode cur=head->next;
      while(NULL !=cur )
	  {
		  cout<<cur->data;
		  if(cur->next != NULL)
		  {
			  cout<<"->";
		  }
		  cur=cur->next;
	  }
	  cout<<"  size="<<head->size;
	  cout<<"\n";

}

void reverse(Lnode head)
{
	assert(head != NULL);
	if(head->size <=1)
	{
		return ;
	}
    Lnode pre=head->next;
	Lnode cur=pre->next;
	pre->next=NULL;
	Lnode nxt=NULL;
	while(cur != NULL)
	{
		nxt= cur->next;
		cur->next=pre;
		pre=cur;
		cur=nxt;
	}
	head->next=pre;
}

void back_calc(Lnode head,int pos)
{
	assert(head != NULL&&head ->next != NULL && pos<=head->size);
	Lnode low=head;
	Lnode fast=head;
	int i=0;
	while(i<pos)
	{
		fast=fast->next;
		++i;
	}
	while(fast!=NULL)
	{
      fast=fast->next;
	  low=low->next;
	}
	cout<<low->data<<endl;
}

int isCircleLink(Lnode head)
{
	assert(head != NULL);
	if(head->next->next == NULL)
	{
		return 0;
	}
      Lnode low =head;
	  Lnode fast=head;

	  while(fast->next!=NULL)
	  {
		   fast=fast->next->next;
		   low=low->next;
		   if(fast == low)//是环
		   {
			   cout<<"是环\n";
			   for(low =head;low != fast;)
			   {
                low=low->next;
				fast=fast->next;
			   }
			   cout<<"相交处的值: "<<low->data<<endl;
                int i=1;
				fast=fast->next;
			   while(low !=fast)
			   {
				   fast=fast->next;
				   ++i;
			   }
			   cout<<"环大小: " <<i<<endl;
			   return 1;
		   }
	  }
	  return 0;
}
int main()
{

  Lnode head;
  init(head);
  int i=0;
  while(i<5)
  {
 pushback(head,i+2);
++i;
  }
  cout<<"print Link :\n";
  print(head);
  cout<<"找倒数第2个数:\n";
    back_calc(head,2);
 cout<<"翻转:\n";
 reverse(head);
 print(head);


 CreatCircle_Link(head,2);
isCircleLink(head);


	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值