首页 > 其他 > 详细

206_反转链表

时间:2021-08-30 06:17:05      阅读:15      评论:0      收藏:0      [点我收藏+]

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

技术分享图片

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

技术分享图片

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

解题思路:

  1. 申请一个pre指向null
  2. 遍历节点到null
  • 先保存当前节点下一个节点

  • 把当前节点的下一节点指向pre

  • 把pre指向当前节点

     

     

class Solution {
    public ListNode reverseList(ListNode head) {
        // corner case
        if (head == null || head.next == null) {
            return head;
        }

        // normal case
        ListNode pre = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}

  

 

206_反转链表

原文:https://www.cnblogs.com/iwyc/p/15196399.html

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