双指针反转

  1. private static ListNode revertNode(ListNode head) {
  2. ListNode pre = null;
  3. ListNode cur = head;
  4. ListNode next;
  5. whilecur != null){
  6. next = cur.next;
  7. cur.next = pre;
  8. pre = cur;
  9. cur = next;
  10. }
  11. return pre;
  12. }

未命名文件 (2).jpg

栈方式

  1. private static ListNode revertNode(ListNode head){
  2. Stack<ListNode> stack = new Stack<>();
  3. while(head != null){
  4. stack.push(head);
  5. head = head.next;
  6. }
  7. ListNode dummyHead = new ListNode(0);
  8. ListNode cur = dummyHead;
  9. while(!stack.isEmpty()){
  10. cur.next = new ListNode(stack.pop().val);
  11. cur = cur.next;
  12. }
  13. return dummyHead.next;
  14. }