问题描述:
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连回去的时候会出现环