[LeetCode]143. Reorder List

发布时间:2020-08-15 22:06:04 作者:風子余
来源:网络 阅读:510

143. Reorder List

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}.


题意:

给定链表L0L1→…→Ln-1Ln,重新整理后输出L0LnL1Ln-1L2Ln-2→…链表。

举例如下:给定链表{1,2,3,4,5}重排后为{1,5,2,4,3}

{1,2,3,4,5,6}重排后为{1,6,2,5,3,4}


思路:

1)链表为空,或者链表只有一个或者两个节点,直接返回即可。

2)获取链表的长度len,把链表分成前后两部分。如果长度为奇数,前部分链表长度为len/2 + 1,后部分长度为len/2。比如{1,2,3,4,5}拆分后前部分链表为{1,2,3}后部分链表为{4,5};如果长度为偶数,前部分链表长度为len / 2 ,后部分长度为 len / 2。比如{1,2,3,4,5,6}拆分后为{1,2,3}和{4,5,6}

3)反转第二部分链表。

4)把第二部分链表插入到第一部分链表的指定位置即可。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
void reorderList(struct ListNode* head)
{
    if ( head == NULL || head->next == NULL || head->next->next == NULL )
    {
        return;
    }
    
    struct ListNode *list  = head;
    int len = 0;
    while ( list )
    {
        list = list->next;
        len += 1;
    }
    
    int key = 0;
    if ( len % 2  == 0 )
    {
        key = len / 2;
    }
    else
    {
        key = (len / 2) + 1;
    }
    
    struct ListNode *second = head;
    list  = head;
    int cnt = 0;
    while ( cnt < key )
    {
        list = second;
        second = second->next;
        cnt += 1;
    }
    list->next = NULL;
    
    list = NULL;
    struct ListNode *next = NULL;
    while ( second )
    {
        next = second->next;
        second->next = list;
        list = second;
        second = next;
    }
    second = list;
    
    next = NULL;
    while ( second )
    {
        next = second;
        second = second->next;
        next->next = head->next;
        head->next = next;
        head = head->next->next;
    }
}


推荐阅读:
  1. Leetcode 之判断字符串是否有效及栈结构
  2. LeetCode之动态规划

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

leetcode lis tc

上一篇:API安全的防御建设

下一篇:Zope的优点和Apache+PHP+MySQL的比较(转)

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》