程序员代码面试指南 2.5:反转部分单向链表

1、思路

  • 需要得到四个节点的位置:反转链表的前一个节点before,反转链表的起始节点start,反转链表的末尾结点end以及反转链表末尾结点的后一个节点after

  • startend之间的链表进行反转,反转后end变成了表头,start变成了表尾;

  • 最后再将这四个节点连接起来即可。

2、代码

list_node * reverse_list(list_node * head, int L, int R)
{
    if (head == nullptr || head->next == nullptr) return head;

    auto dummy = new list_node;             //定义虚拟头结点,因为反转链表可能从第一个元素开始
    dummy->next = head;

    auto before = dummy, end = head;        //注意before与end的初始位置
    while ( -- L  && before->next != nullptr) before = before->next;
    while ( -- R && end->next != nullptr) end = end->next;

    auto start = before->next, after = end->next;

    auto pre = start, cur = start->next;    //反转链表的模板
    while (cur != after)
    {
        auto ne = cur->next;
        cur->next = pre;
        pre = cur, cur = ne;
    }

    before->next = end;     //连接表头
    start->next = after;    //连接表尾

    return dummy->next;
}
#腾讯##华为##面经##校招##运营#
全部评论
你也太强了吧,校友!
点赞 回复
分享
发布于 2019-10-20 21:18
优秀,腾讯大佬
点赞 回复
分享
发布于 2019-10-20 23:26
滴滴
校招火热招聘中
官网直投
哇 大佬
点赞 回复
分享
发布于 2019-10-21 17:21

相关推荐

比亚迪深圳规划院 产品经理 0.9×1.36×12
点赞 评论 收藏
转发
11 31 评论
分享
牛客网
牛客企业服务