特殊单链表的一些操作

来源:互联网 发布:swfobject.js播放 编辑:程序博客网 时间:2024/06/06 04:32
1,建一个有环单链表:


#include<iostream>
using namespace std;
#include<stack>
struct Node
{
int _data;
struct Node *next;




};




typedef Node *PList;
Node* CreatNode(int x)//创建节点
{




Node *tmp = new Node;
tmp->_data = x;
tmp->next = NULL;
return tmp;




}
void Pushback(PList &head, int x)//尾插
{
if (head == NULL)
{
head = CreatNode(x);




}
else
{
Node * tail = head;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = CreatNode(x);
}
}
Node* Find(PList head, int x)
{
Node *cur = head;
while (head != NULL)
{
if (cur->_data == x)
{
return cur;
}
cur = cur->next;








}
}void main()
{




PList list1;
list1= NULL;
Node *cur = NULL;
Node *cur1 = NULL;




Pushback(list1, 1);
Pushback(list1, 2);
Pushback(list1, 3);
Pushback(list1, 4);
Pushback(list1, 5);
Pushback(list1, 6);
Pushback(list1, 7);
Pushback(list1, 8);
cur=Find(list1, 4);//找到两个节点,把他们的next更改。
cur1=Find(list1, 8);
cur1->next = cur;
}






2,检查是否有环,有环输出环的节点个数:


int CheackCyce(PList head)
{
Node *fast = head;
Node *slow = head;
while (fast&&fast->next)
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
{
int count = 1;
Node *cur = slow;
while (cur->next != slow)
{
++count;
cur = cur->next;
}
return count;
}


}
return -1;
}
3,找到环的入口点:




Node *FindEntry(PList head)//找到环的入口点
{
Node *fast = head;
Node *slow = head;
while (fast&&fast->next)
{
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
{
fast = head;
while (fast != slow)
{


fast = fast->next;
slow = slow->next;
}
return fast;




}






}


}//求入口点,第一次的相遇节点为meetNode//fast=k+l+x slow=k+x;k+x=L;注意环很小时候




快指针不止走了一圈,




//fast=k+nl+x,slow=k+x;k+nl+x=2(k+x),nl=k+x;(K位起点到环起点的距离。x为环的起点到相遇点,l为环的长度) k=nl-x;
//
4,判断两个单链表是否相交,
int Iscomp(PList head1, PList head2)//(无环)是否相交
{
Node *cur1 = head1;
Node *cur2 = head2;
if (head1 == NULL)
{
return 0;
}
if (head2 == NULL)
{
return 0;
}
while (cur1&&cur1->next)
{
cur1 = cur1->next;


}
while (cur2&&cur2->next)
{
cur2 = cur2->next;


}
while (cur1 ==cur2)
{
return 1;
}
return -1;


}
5,两个单链表相交的起点:
Node * copx(PList head1, PList head2)//(无环)是否相交
{
int count1 = 0;
int count2 = 0;
int sum = 0;
Node *cur1 = head1;
Node *cur2 = head2; 
Node *cur3 = head1;
Node *cur4 = head2;
if (head1 == NULL)
{
return 0;
}
if (head2 == NULL)
{
return 0;
}
while (cur1&&cur1->next)//计算链表1的长度
{
cur1 = cur1->next;
count1++;


}
while (cur2&&cur2->next)//计算链表2的长度
{
cur2 = cur2->next;
count2++;


}
if (count1 > count2)//求出链表1比链表2长多少
{
sum = count1 - count2;
while (sum--)//让链表一先走比链表2长度的距离
{
cur3 = cur3->next;
}
}
else
{
sum = count2 - count1;
while (sum--)
{
cur4 = cur4->next;
}
}
while (cur3 != cur4)//距离相同,所以同时到达入口点;
{
cur3 = cur3->next; 
cur4 = cur4->next;


}
return cur3;

}
0 0
原创粉丝点击