[LeetCode] Reorder List

来源:互联网 发布:网络编程实用教程第3版 编辑:程序博客网 时间:2024/05/17 07:46

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

class Solution {public:    void reorderList(ListNode *head) {        if(head == NULL || head -> next == NULL) return;        ListNode *mid = getMid(head);        ListNode *back = reverse(mid -> next);        mid -> next = NULL;        ListNode *cur = new ListNode(-1);        while(head && back){            ListNode *tmpa = head -> next;            head -> next = back;            ListNode *tmpb= back ->next;            back ->next = tmpa;            head = tmpa;            back = tmpb;        }    }    ListNode *getMid(ListNode *head){        ListNode *p = head;        ListNode *q = head;        while(q -> next && q -> next ->next){            p = p -> next;            q = q -> next ->next;        }        return p;    }        ListNode *reverse(ListNode *head){        if(head == NULL)            return NULL;                    ListNode* p = head->next;          head->next = NULL;                    while(p != NULL){              ListNode* tmp = p;              p = p->next;              tmp->next = head;              head = tmp;          }          return head;      }};


0 0