Reverse Linked List
Difficulty:Easy
Reverse a singly linked list.
反向单链表。
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Code No.1
Java
Runtime: 296 ms
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode prev = null;
ListNode next = null;
while(cur != null) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}