Leetcode 206: Reversed Linked List

问题描述:
Given the head of a singly linked list, reverse the list, and return the reversed list. 反转单链表

思路:
反转指针时会丢失之后的位置,所以要先把下一个位置保存好。另外是检查边界情况,是细节问题但不难

上代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head==null) return null;
        if (head.next==null) return head;
        
        ListNode current_node = head.next;
        **head.next = null;**
        ListNode next_node = null;
        
        while(current_node.next!=null){
            next_node = current_node.next; 
            current_node.next = head;
            head = current_node;
            current_node = next_node;
        }
        current_node.next = head;
        return current_node;
    }
}

时间复杂度:O(n)

二刷这道题没有用明显更高级的写法,就是感觉写法更清晰了,暴力地罗列出三指针没什么不好,明确说明哪个是前,中,后,再微调一下边界情况就好了。

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null) return null;
        if(head.next==null) return head;
        ListNode last = head;
        ListNode current = head.next;
        ListNode next = head.next.next;
        **head.next=null;**
        while(next!=null){
            current.next = last;
            last = current;
            current = next;
            next = current.next;
        }
        current.next = last;
        return current;
    }
}

值得注意的是在最一开始last.next要手工设为null,否则current.next连回去的时候会出现环

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值