zoukankan      html  css  js  c++  java
  • LeetCode 143. 重排链表

    题目链接:https://leetcode-cn.com/problems/reorder-list/

    给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
    将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例 1:

    给定链表 1->2->3->4, 重新排列为 1->4->2->3.
    示例 2:

    给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

    小结:感觉这题比较好,虽然题目简单也易理解,但是有很多常规操作,先是快慢指针,其次是逆置链表,最后是俩链表的合并。

     1 void reorderList(struct ListNode* head){
     2     if(head==NULL||head->next==NULL) return head;
     3     struct ListNode *slow=head,*fast=head,*q,*p,*head1,*head2;
     4     while(fast->next&&fast->next->next){
     5         slow=slow->next;
     6         fast=fast->next->next;
     7     }
     8     head1=head;
     9     head2=slow->next;
    10     slow->next=NULL;
    11     struct ListNode *pre=NULL,*cur=head2,*tmp;
    12     while(cur){
    13         tmp=cur->next;
    14         cur->next=pre;
    15         pre=cur;
    16         cur=tmp;
    17     }
    18     head2=pre;
    19     q=head1,p=head2;
    20     struct ListNode *new=(struct ListNode*)malloc(sizeof(struct ListNode));
    21     cur=new;
    22     while(q&&p){
    23         cur->next=q;
    24         q=q->next;
    25         cur=cur->next;
    26         cur->next=p;
    27         p=p->next;
    28         cur=cur->next;
    29     }
    30     if(q) cur->next=q;
    31     return new->next;
    32 }
  • 相关阅读:
    eclipse使用svn
    yum安装mysql
    spring中aop使用
    mybatis定义拦截器
    横扫页面的三大标签
    springmvc日期格式化
    springmvc笔记
    springboot跳转jsp页面
    常用网址
    CentOS Android Studio桌面图标的创建
  • 原文地址:https://www.cnblogs.com/shixinzei/p/12425648.html
Copyright © 2011-2022 走看看