Reorder List leetcode 易出错点已标记

来源:互联网 发布:windows7 apache 编辑:程序博客网 时间:2024/06/05 06:13
#include <iostream>using namespace std;/**Reorder List Total Accepted: 23179 Total Submissions: 113917 My Submissions Question SolutionGiven a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…You must do this in-place without altering the nodes' values.For example,Given {1,2,3,4}, reorder it to {1,4,2,3}.思路:找到链表中点,切断,后面的逆转,组成新链表*/struct ListNode {      int val;      ListNode *next;      ListNode(int x) : val(x), next(NULL) {}  };class Solution {public:    void reorderList(ListNode *head) {      if(head == NULL || head->next == NULL)        return ;      ListNode *d =  new ListNode(-1);      d->next = head;      ListNode *f,*s,*pre;      f = head;      s = head;      while(f && f->next ){    //注意这里易错   f->next->next 可能f->next=NULL,则报错        pre = s;              // //注意这里易错  循环出来,s跳到s后面的元素        f = f->next->next;        s = s->next;      }//出来之后,s指向的是链表中间      ListNode *lhead = new ListNode(-1);      lhead->next = s; //后面链的头      pre->next = NULL;      ListNode *p = lhead;      ListNode *reversehead = new ListNode(-1);      while(p->next !=NULL){        ListNode *node = new ListNode(p->next->val);        node->next = reversehead->next;        reversehead->next = node;        p = p->next;      }//reversehead 得到翻转后的后半链表      /*        for(ListNode *pp = reversehead->next;pp != NULL;pp = pp->next)            cout<<pp->val<<" ";        cout<<endl;    */      //重新赋值      s = d->next;      p = reversehead->next;      while(s->next){        ListNode *tmp = s->next;        s->next = p;        p = p->next;        s->next->next = tmp;        s = tmp;      }      s->next = p;      /**这一步很关键,主要是因为1->2->3->4 s最后停在3,f停在4后面的NULL,则前半为1->2, 后半为 3->4         reverse后,4->3 ;p->4->3         s= 1->2         tmp=2,1->3->2         s=2         此时,s->next == NULL,故循环直接跳出,所以需要加最后一句来接上最后的4      */    }};int main(){    ListNode *head= new ListNode(1);    ListNode *n1 = new ListNode(2);    ListNode *n2 = new ListNode(3);    ListNode *n3 = new ListNode(4);    ListNode *n4 = new ListNode(5);    ListNode *n5 = new ListNode(6);    head->next = n1;    n1->next = n2;    n2->next = n3;    n3->next = n4;    n4->next = n5;    for(ListNode *p = head;p != NULL;p = p->next)        cout<<p->val<<" ";    cout<<endl;    Solution s;     s.reorderList(head);    for(ListNode *p=head;p!=NULL;p=p->next)        cout<<p->val<<" ";    return 0;}

0 0
原创粉丝点击