1.建立虚拟头结点实现反转
使用了虚拟节点(指向头结点)(该题目里头结点存储数据)
/**
* 方法1:虚拟结点,,并复用已有的结点
*
* @param head
* @return
*/
public static ListNode reverseListByDummyNotCreate(ListNode head) {
ListNode ans = new ListNode(-1);
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = ans.next;
ans.next = cur;
cur = next;
}
return ans.next;
}
2.直接操作链表实现反转(不使用虚拟头结点)(理解的基础上背)
/**
* 方法3:不适用头结点,基本的反转方法
*
* @param head
* @return
*/
public static ListNode reverseListSimple(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
3.使用递归(仅参考)
/**
* 方法4:通过递归实现链表反转
*/
public static ListNode reverseListByRecurse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseListByRecurse(head.next);
head.next.next = head;
head.next = null;
return newHead;
}