lintcode-99-重排链表

99-重排链表

给定一个单链表L: L0→L1→…→Ln-1→Ln,
重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点值的情况下进行原地操作。

样例

给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null。

挑战

Can you do this in-place without altering the nodes' values?

标签

链表

思路

先将链表整体一分为二,然后将后半段链表逆序,再依次插入前半段节点中。

code

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: void
     */
    void reorderList(ListNode *head) {
        // write your code here
        if(head != NULL && head->next != NULL) {
            ListNode *fast = head, *slow = head, *temp = head;
            while(fast != NULL && fast->next != NULL) {
                temp = slow;
                slow = slow->next;
                fast = fast->next->next;
            }
            temp->next = NULL;

            slow = reverse(slow);
            
            ListNode *newHead = head;

            while(newHead != NULL) {
                if(newHead->next == NULL) {
                    newHead->next = slow;
                    break;
                }
                else{
                    temp = newHead->next;
                    newHead->next = slow;
                    slow = slow->next;
                    newHead->next->next = temp;
                    newHead = temp;
                }
            }
        }
    }
    
    ListNode *reverse(ListNode *head) {
        ListNode *l1=NULL,*l2=NULL,*l3=NULL;

        l1 = head; 
        if(l1 == NULL || l1->next == NULL) {
            return l1;
        }
        l2 = l1->next;
        if(l2->next == NULL) {
            l2->next = l1;
            l1->next = NULL;
            return l2;
        }
        l3 = l2->next;
        if(l2->next != NULL) {
            while(l2 != l3) {
                l2->next = l1;
                if(l1 == head) {
                    l1->next = NULL;
                }
                l1 = l2;
                l2 = l3;
                if(l3->next != NULL) {
                    l3 = l3->next;
                }
            }
            l2->next = l1;
            return l2;
        }
    }
};
posted @ 2017-07-12 17:25  LiBaoquan  阅读(634)  评论(0编辑  收藏  举报