生活随笔
收集整理的這篇文章主要介紹了
单链表查找中间结点
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
單鏈表查找中間結(jié)點
題目描述:隨機生成20個元素,構(gòu)成一個鏈表,查找鏈表中間結(jié)點的值。
方法:快慢指針法
C++實現(xiàn)如下:
#include<iostream>
#include<ctime>
using namespace std
;
#define SIZE 20
class ListNode
{
public:int Data
;ListNode
* Next
;
};
ListNode
* CreateList(int size
)
{ListNode
* head
= new ListNode
;head
->Next
= NULL;for (int i
= 0; i
< size
; i
++){ListNode
* L
= new ListNode
;L
->Data
= rand() % 100 + 1; L
->Next
= head
->Next
;head
->Next
= L
;}return head
;
}
int main()
{srand((unsigned int)time(NULL));ListNode
* L
= CreateList(SIZE
);ListNode
* p
= L
->Next
;while (p
!= NULL){cout
<< p
->Data
<< " ";p
= p
->Next
;}cout
<< endl
;ListNode
*fast
, *low
;fast
= L
; low
= L
;while (fast
->Next
!= NULL){if (fast
->Next
->Next
!= NULL){fast
= fast
->Next
->Next
;low
= low
->Next
;}else{fast
= fast
->Next
;}}cout
<< "中間結(jié)點的值為:" << low
->Data
<< endl
;system("pause");return 0;
}
總結(jié)
以上是生活随笔為你收集整理的单链表查找中间结点的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。