https://leetcode-cn.com/problems/reverse-linked-list/submissions/
1、双指针
public static ListNode reverseList(ListNode head) {
ListNode pre;
ListNode cur;
ListNode newHead = null;
cur = head;
pre = cur.next;
while(pre != null) {
cur.next = newHead;
newHead = cur;
cur = pre;
pre = pre.next;
}
cur.next = newHead;
return cur;
}
自己画图:
执行结果:
2、递归
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode ret = reverseList(head.next);
head.next.next = head;
head.next = null;
return ret;
}