
My code:
/**
* 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) {
if (head == null || head.next == null)
return head;
// /** iterative */
// ListNode pre = head;
// ListNode curr = head.next;
// while (curr != null) {
// ListNode temp = curr.next;
// curr.next = pre;
// pre = curr;
// curr = temp;
// }
// head.next = null;
// return pre;
/** recursive */
ListNode tail = head;
while (tail.next != null)
tail = tail.next;
reverse(head);
return tail;
}
private ListNode reverse(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode pre = reverse(head.next);
pre.next = head;
head.next = null;
return head;
}
}
這道題目用兩種方法實現(xiàn)了反轉鏈表。
一種是直接遍歷,一邊遍歷一邊反轉。
一種是,用遞歸實現(xiàn)反轉。
Anyway, Good luck, Richardo!