简单分为两类:带虚拟头节点和不带虚拟头节点
1.带虚拟头节点
建立一个虚拟头节点后,依次从原链表上拆下来节点,最终实现反转。具体实现代码如下
public static Node reverseList(Node head){
Node ans = new Node(-1);
Node cur = head;
while (cur != null){
Node next = cur.next;
ans.next = cur;
cur = next;
}
return ans.next;
}
初始情况为ans指向了第一个节点,cur指向了第二个节点。最后返回ans指向的反转后链表的头节点。
2.不带虚拟头节点
public static Node reverseList(Node head){
Node prev = null;
Node cur = head;
while (cur != null){
Node next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
建立三个节点,prev ,cur,next。