实例:输入head=[ 1,2,3,4,5]
输出:[5,4,3,2,1]
虚拟头结点实现链表反转
思路:建立虚拟头节点 dummy ,遍历要反转的链表head,cur为当前遍历到的链表节点,每次遍历一个节点,首先得到cur的下一个节点temp方便继续遍历(temp = cur.next),然后把cur的后继指针指向dummy的下一个节点(cur.next = dummy.next),再把dummy的后继指针指向cur(dummy.next = cur),最后 cur 赋值为 temp (cur = temp),继续遍历...
public NodeList reversalByDummy(NodeList head){
//定义新链表的节点 dummy
NodeList dummy =new NodeList(0);
NodeList cur = head;
//遍历链表
while (cur != null){
//下一个节点
NodeList temp = cur.next;
cur.next = dummy.next;
dummy.next=cur;
cur=temp;
}
return dummy.next;
}
不带虚拟头结点实现链表反转
思路:定义旧链表首节点cur,下一个要调整的旧链表节点temp,新链表的首节点prev;遍历要反转的链表,每遍历一个链节点,先获取此刻节点cur的下一个节点temp(方便下一次遍历),改变cur的后继节点的指针,并调整新旧链表的表头...
public NodeList reversalByNotDummy(NodeList head){
//定义旧链表首节点cur,下一个要调整的旧链表节点temp,新链表的首节点prev
NodeList cur = head;
NodeList prev = null;
while (cur!=null){
NodeList temp = cur.next;
cur.next = prev;
prev=cur;
cur=temp;
}
return prev;
}