143. Reorder List

1,找到中间节点,并把前半部的链表以NULL结尾,
2,把后半部的链表反转,
3,前后合并两个链表

另外值得注意的是,对于中间节点的寻找,第二种方法中间总是中间位置偏后,第一种对于奇数个数的中间节点,偏前。

        fast = fast->next;
        if(fast){
            fast = fast->next;
            slow = slow->next;
        }
{1 2 3 4} slow = 3 
{1 2 3}  slow = 2

        fast = fast->next;
        if(fast){
            fast = fast->next;      
        }
        slow = slow->next;
{1 2 3 4} slow = 3 
{1 2 3}  slow = 3
struct ListNode * reverse(struct ListNode *head)
{
    if(head == NULL || head->next == NULL)
        return head;
    struct ListNode * prev, *curr, *next;
    curr = head;
    prev = next = NULL;

    while(curr){
        next = curr->next;
        curr->next = prev;
        prev =  curr;
        curr = next;
    }


    return prev;
}

void reorderList(struct ListNode* head) {

    if(head == NULL || head->next == NULL)
        return head;
    struct ListNode *fast, *slow;
    fast = head->next;
        slow = head;
    while(fast){
        fast = fast->next;
        if(fast){
            fast = fast->next;
            slow = slow->next;
        }

    }

    struct ListNode *tmp = slow;
    slow = slow->next;
    tmp->next = NULL;
    struct ListNode  *front = head;
    struct ListNode *back = reverse(slow);

    struct ListNode *dummy = calloc(1, sizeof(struct ListNode));
    struct ListNode *last = dummy;

    while(1){
        if(front&&back){
            last->next = front;
            front = front->next;
            last = last->next;

            last->next = back;
            back = back->next;
            last = last->next;
        }else if(front){
            last->next = front;
            front = front->next;
            last = last->next;

        }else if(back){
            last->next = back;
            back = back->next;
            last = last->next;
        }else{
            last->next = NULL;
            break;
        }
    }

    return dummy->next;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it ...
    ShutLove阅读 361评论 0 0
  • 一、题目 二、解题 把链表组成一个环状,1,2,3,4->1,4,2,3 定义两个方向的指针,第一个方向从头往后,...
    乐乐可爱睡觉阅读 800评论 0 1
  • 原题 给定一个单链表L: L0→L1→…→Ln-1→Ln,重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2...
    Jason_Yuan阅读 424评论 0 0
  • 题目描述:给链表如L: L0→L1→…→Ln-1→Ln,将其重新排序为L0→Ln→L1→Ln-1→L2→Ln-2→...
    Nautilus1阅读 388评论 0 0
  • 对于我这个从小在广东长大的人来说饺子是兴致来了会去吃一顿的东西。我们这片对饺子没有那么感冒。 到后来我来到深圳这个...
    蔡清荷阅读 278评论 0 0