876. Middle of the Linked List

时间复杂度为O(n) ,空间复杂度为O(1),双指针,代码如下:

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
     ListNode *f,*s;
     f=s=head;
       while(s!=NULL && s->next!=NULL){
         s=s->next;
         s=s->next;
          f=f->next;

       }
       ListNode *tmp=f;
       while(tmp!=NULL){
       cout<<tmp->val<<" ";
       tmp=tmp->next;
       }
       return f;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36353434/article/details/81291173