Skip to content

Instantly share code, notes, and snippets.

@xuzheng465
Last active February 4, 2022 02:30
Show Gist options
  • Save xuzheng465/c4d560f1a50aef3cc0bd16ae699f1a27 to your computer and use it in GitHub Desktop.
Save xuzheng465/c4d560f1a50aef3cc0bd16ae699f1a27 to your computer and use it in GitHub Desktop.
class Solution {
// 头插法
public ListNode reverseList(ListNode head) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head;
while (cur!=null && cur.next!=null) {
ListNode newHead = cur.next;
cur.next = cur.next.next;
newHead.next = pre.next;
pre.next = newHead;
}
return dummy.next;
}
//
public ListNode reverseList2(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode tmp = null;
while (cur != null) {
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment