手写链表反转
1借助虚拟头结点
头插法,将链表一个一个连到虚拟头结点后面
public static ListNode reverseListByDummyNotCreate(ListNode head) { ListNode dummy = new ListNode(0); ListNode cur = head; while(cur!=null){ ListNode next=cur.next; //先保存后一个结点 cur.next=dummy.next; //插入 dummy.next=cur; cur=next; //向后移动 } }
2穿针引线
public static ListNode reverseListSimple(ListNode head) { ListNode cur=head,pre=null; while(cur!=null){ ListNode next=cur.next; cur.next=pre; pre=cur; //pre.next=cur;错误的 cur=next; } return pre; }