ID | Title | Difficulty | |
---|---|---|---|
Loading... |
206. Reverse Linked List
Easy
LeetCode
Linked List, Recursion
Problem
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Code
/**
* 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 pre = null;
while(head != null){
// 相当于改变了指向的方向
// 1->2 变成了 1<-2
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
}
按 <- 键看上一题!
205. Isomorphic Strings
按 -> 键看下一题!
207. Course Schedule