Leetcode 206. Reverse Linked List
题目
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL思路
解答
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode prev = null;
ListNode curr = head;
while (curr.next != null) {
ListNode next = curr.next;
curr.next = prev; // Step1: Reverse link
prev = curr; // Step2: Proceed prev
curr = next; // Step 3: Proceed curr
}
curr.next = prev;
return curr;
}
}Complexity Analysis
拓展
总结
Last updated
