1.建立虚拟头结点辅助实现链表反转
流程图
代码实现
public ListNode reverseLinkList(ListNode head){
ListNode tmp = new ListNode(-1);
ListNode cur = head;
while (cur!=null){
ListNode next = cur.next;
cur.next = tmp.next;
tmp.next = cur;
cur = next;
}
return tmp;
}
2.直接操作链表实现反转
反转前后的结构和指针位置
执行期间的过程示意图
public ListNode reverseList(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.拓展(通过递归来实现反转)
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}