【Leetcode】链表的中间结点(每日一题)


题目链接:链表的中间结点


题意:给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。


题解:两个解法都很经典。

1、先遍历记录链表长度,再走到len/2的位置就可以了。

2、用两个指针,前一个走两步,后一个走一步。这样前面的走到末尾时,后面的刚好到中间。


代码

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* middleNode(ListNode* head) {
12         ListNode *cur = head;
13         int len = 0;
14         while(cur!=NULL){
15             cur = cur->next;
16             len++;
17         }
18         len = len/2;
19         while(len--){
20             head = head->next;
21         }
22 
23         return head;
24     }
25 };
26 
27 
28 OR
29 
30 /**
31  * Definition for singly-linked list.
32  * struct ListNode {
33  *     int val;
34  *     ListNode *next;
35  *     ListNode(int x) : val(x), next(NULL) {}
36  * };
37  */
38 class Solution {
39 public:
40     ListNode* middleNode(ListNode* head) {
41         ListNode* pre = head;
42         ListNode* last = head;
43         while(pre && pre->next){
44             last = last->next;
45             pre = pre->next->next;
46         }
47         return last;
48     }
49 };

猜你喜欢

转载自www.cnblogs.com/Asumi/p/12555630.html