题目:206. 反转链表
反转一个单链表。
方式一(迭代)
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode curr = head;
ListNode prev = null;
while (curr != null) {
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
方式二(递归)
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode res = reverseList(head.next);
head.next.next = head;
head.next = null;
return res;
}