快慢指针寻找链表中间值

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

猜你喜欢

转载自blog.csdn.net/qq_36162036/article/details/89188827