LeetCode 876. 链表的中间结点

题目链接:https://leetcode-cn.com/problems/middle-of-the-linked-list/

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

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

 

示例 1:

输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
示例 2:

输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
 

提示:

给定链表的结点数介于 1 和 100 之间。

我写的:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* middleNode(struct ListNode* head){
 9     if(head==NULL||head->next==NULL) return head;
10     int num=0;
11     struct ListNode *p=head;
12     while(p){
13         if(p) num++;
14         p=p->next;
15     }
16     num=num/2+1;
17     p=head;
18     while(--num){
19         p=p->next;
20     }
21     return p;
22 }

%大佬写的:(快慢指针C++)

 1 class Solution {
 2 public:
 3     ListNode* middleNode(ListNode* head) {
 4         ListNode* slow = head;
 5         ListNode* fast = head;
 6         while (fast != NULL && fast->next != NULL) {
 7             slow = slow->next;
 8             fast = fast->next->next;
 9         }
10         return slow;
11     }
12 };

 自行敲一哈(补个C)

 1 struct ListNode* middleNode(struct ListNode* head){
 2     if(head==NULL||head->next==NULL) return head;
 3     struct ListNode *slow=head;
 4     struct ListNode *fast=head;
 5     while(fast!=NULL&&fast->next!=NULL){
 6         slow=slow->next;
 7         fast=fast->next->next;
 8     }
 9     return slow;
10 }

 

posted @ 2019-08-15 21:27  wydxry  阅读(227)  评论(0编辑  收藏  举报
Live2D