876单链表--返回链表中间位置的结点

1、思路:自己想出来的是暴力法,用到双指针p1,p2;看了解析还有一种快慢指针法,慢指针走一步,快指针走两步!!分奇偶讨论!

  • 第一个指针p1历求出链表的长度n
  • 考虑到n的奇偶性质
  • 如上图所示

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         if(head->next==NULL)return head;
13         ListNode *t=head;
14         ListNode *p=head ;
15         int n=0;
16         while(t!=NULL){n=n+1;t=t->next;}
17         int cout=(n/2);
18        while(cout!=0&&p!=NULL){
19             p=p->next;
20            cout=cout-1;
21         }
22         return p;
23     }
24 };

 3、快慢指针解法(也可以用来求链表最后n个结点)

 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         if(head->next==NULL)return head; //只有一个结点的情况
13         ListNode *slow=head;//慢指针
14         ListNode *fast=head ;//快指针
15         while(fast->next!=NULL&&fast->next->next!=NULL){
16             slow=slow->next;
17             fast=fast->next->next;
18         }
19         if(fast->next!=NULL){//判断链表长度是奇数吗?
20             slow=slow->next;
21         }
22         return slow;
23     }
24 };
原文地址:https://www.cnblogs.com/hehesunshine/p/11631277.html