链表的中间节点

原题:
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。

例如:
1.给定 序列 [1,2,3,4,5] 则返回 3;
2.给定 序列 [1,2,3,4,5,6] 则返回 4;

思路: 定义两个指针,一个每次加一,另外一个每次加二。当第二个指针指向链表最末尾时,结束循环;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        if(!head->next)
            return head;
        ListNode* pnext = head;
        ListNode* ppnext = head->next;
        while(ppnext)
        {
            pnext = pnext->next;
            if(ppnext->next)
                ppnext = ppnext->next->next;
            else 
                return  pnext;
        }
        return pnext;
    }
};
发布了2 篇原创文章 · 获赞 0 · 访问量 24

猜你喜欢

转载自blog.csdn.net/weixin_46589552/article/details/105061069