链表反转
使用虚拟头节点
从head链表中一个一个往虚拟头节点链表上接
/**
* 方法1:虚拟结点,,并复用已有的结点
*
* @param head
* @return
*/
public static ListNode reverseListByDummyNotCreate(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = dummy.next;
dummy.next = cur;
cur = next;
}
return dummy.next;
}
不使用虚拟头节点
定位pre,cur和temp节点,分别为前一个节点,当前节点和后一个节点,然后改变指向。
- 先将temp节点后移 temp = temp.next;
- 当前节点指向前一个节点 cur.next = pre;
- 前一个节点后移 pre = cur;
- 当前节点后移 cur = temp;
3和4不能换位置,否则前一个节点就不是移动一个节点了
/**
* 方法3:不使用头结点,基本的反转方法
*
* @param head
* @return
*/
public static ListNode reverseListSimple(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode temp = head;
ListNode cur = head;
ListNode pre = null;
while (temp != null) {
temp = temp.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}