★leetcode★ reorder-list

题目:

Given a singly linked list LL 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.

 

 

(这个题目没有头结点)

思路:

  1. 通过快慢指针找出中心点位置;
  2. 把链表分成两部分;
  3. 对后一半链表逆序;
  4. 那后一半链表插入到前一半中,得到结果
     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     void reorderList(ListNode *head)
    12     {
    13         if(head == NULL || head->next == NULL || head->next->next == NULL)
    14             return;
    15         ListNode *slow, *fast, *mid;
    16         slow = head;
    17         fast = head->next;
    18         while(fast != NULL && fast->next != NULL)
    19         {
    20             slow = slow->next;
    21             fast = fast->next->next;
    22         }
    23 
    24 
    25         mid = slow;
    26         ListNode *Back, *p;
    27         Back = mid->next;//后半链表开头
    28         mid->next = NULL;
    29         p = Back->next;
    30         Back->next = NULL;
    31         //后半链表逆序,后半链表Back
    32         while(p)
    33         {
    34             ListNode *tmp;
    35             tmp = p->next;
    36             p->next = Back;
    37             Back = p;
    38             p = tmp;
    39         }
    40 
    41 
    42 
    43         ListNode *Front = head;
    44         while(Front != NULL && Back != NULL)
    45         {
    46             ListNode *temp1, *temp2;
    47             temp1 = Front->next;
    48             temp2 = Back->next;
    49             Front->next = Back;
    50             Back->next = temp1;
    51             Front = temp1;
    52             Back = temp2;
    53         }
    54 
    55     }
    56 };

     

     

posted on 2017-06-22 17:01  xdzhanght  阅读(146)  评论(0编辑  收藏  举报

导航