首页 > 其他 > 详细

剑指offer 15.反转链表

时间:2020-02-28 13:27:26      阅读:57      评论:0      收藏:0      [点我收藏+]

15.反转链表

题目

输入一个链表,反转链表后,输出新链表的表头。

思路

翻转链表并不是很难,只需要注意一下特殊情况,这里设置两个空节点存储前一个结点和后一个结点。
头结点为空直接结束,不为空就开始循环,假设链表为0->1,head=0,next=null,pre=null;然后next=1,head.next=null(最后一位没有子节点),pre=0,head=1;然后next=null,head.next=0,pre=1,head=null,跳出循环,头结点为pre(1),结束。
最后返回的应该是pre不是head,因为原本尾结点现在是pre,多走了一步,head归为null了。

代码

  public class ListNode {

    int val;
    ListNode next = null;

    ListNode(int val) {
      this.val = val;
    }
  }

  public ListNode ReverseList(ListNode head) {
    if (head == null) {
      return null;
    }
    ListNode pre = null;
    ListNode next = null;
    while (head != null) {
      next = head.next;
      head.next = pre;
      pre = head;
      head = next;
    }
    return pre;
  }

剑指offer 15.反转链表

原文:https://www.cnblogs.com/blogxjc/p/12376452.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!