链表操作之快慢指针

来源:互联网 发布:网络安全法宣传周展板 编辑:程序博客网 时间:2024/05/17 06:25

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


代码:


#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;}


1 0
原创粉丝点击