重新整理链表

要求

例如原链表为 1->2->3->4->5 ,重新整理后为 1->4->2->5->3

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* 跟着算法走一遍就知道如何重新整理
**/
#include <iostream>
using namespace::std;

struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    //1,2,4,5 -> 1,4,2,5  1,2,3,4,5 -> 1,4,2,5,3
    int lengthOfList(ListNode* head){
        ListNode* p = head;
        int count = 0;
        while (p!=NULL) {
            p = p->next;
            count++;
        }
        return count;
    }

    /**
    * 翻转链表
    **/
    ListNode* reverseList(ListNode* head){
        ListNode* pre = head;
        ListNode* p = pre->next;
        ListNode* next = NULL;
        while (p!=NULL) {
            next = p->next;
            p->next = pre;
            pre = p;
            p = next;
        }
        head->next=NULL;
        return pre;
    }

    void reorderList(ListNode* head) {
        if (head==NULL||head->next==NULL) {
            return;
        }else{
            int n = lengthOfList(head);
            int half = n/2;
            if (n%2!=0) {
                half++;
            }
            ListNode* leftEnd = head;
            for (int i=0; i<half-1; i++) {
                leftEnd = leftEnd->next;
            }

            ListNode* rightStart = leftEnd->next;
            rightStart = reverseList(rightStart);

            leftEnd->next =NULL;
            ListNode* left = head;
            ListNode* right = rightStart;
            ListNode* next = NULL;

            //重新链接
            bool flag = true;
            while (right!=NULL) {
                if (flag) {
                    next = left->next;
                    left->next = right;
                    left = next;
                }else{
                    next = right->next;
                    right->next = left;
                    right = next;
                }
                flag = !flag;
            }
        }

    }
};
int main(int argc, const char * argv[]) {
    return 0;
}

Comments