您的位置:首页 > 其它

快慢指针寻找链表中间值

2019-04-10 17:25 63 查看
版权声明:转载请注明出处 https://blog.csdn.net/qq_36162036/article/details/89188827
[code]#include <iostream>
#include <string>
using namespace std;
typedef struct LNode
{
int data;//Node data field
struct LNode *next;//Pointer field of the node
}LNode, *LinkList;//linklist is the pointer to LNode;
void createlist_R(LinkList &L){
int n;
LinkList s, r;
L = new LNode;
L->next = NULL;//create a linklist with a head;
r = L;
cout << "please input the number of figure" << endl;
cin >> n;
cout << "Please enter non-decreasing integers in order" << endl;
//creat the linklist
while (n--){
s = new LNode;
cin >> s->data;
s->next = NULL;
r->next = s;
r = s;
}
}
LinkList findmiddle(LinkList L){
LinkList q, s;
q = L;//P为快指针
s = L;//s为慢指针
while (q != NULL&&q->next != NULL){
q=q->next->next;
s=s->next;
}
return s;
}
void LinkList_L(LinkList L){
LinkList P;
P = L->next;
while (P){
cout << P->data << endl;
P = P->next;
}
}
int main(){
LinkList L,mid;
createlist_R(L);//创建单链表
LinkList_L(L);
mid = findmiddle(L);
cout << "快慢法得到的单链表节点数据为:" << mid->data << endl;
return 0;
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: