特殊单链表的一些操作

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;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值