將一個鏈表反轉輸出,鏈表沒有head結點。
思路
因為沒有頭節點,不能用頭插法來實現反轉,但可以采用差不多的思想。
ListNode的結構
public class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
算法具體代碼
public ListNode ReverseList(ListNode head) {
ListNode front, nextNode;
if (head == null) {
return null;
}
front = head;
while (head.next != null) {
nextNode = head.next;
head.next = nextNode.next;
nextNode.next = front;
front = nextNode;
}
return front;
}
代碼中利用了nextNode來存儲當前結點的下一個結點,已經新的頭節點front。
假設輸入的鏈表為1 -> 2 -> 3 -> 4 -> 5
,那么head結點和front結點的值為1,經過head.next = nextNode.next
之后,head結點的下一個結點由2變為了3,nextNode.next = front
,鏈表就變為了2 -> 1-> 3 -> 4 -> 5
,再修改front結點為2。這樣經過一次遍歷,鏈表反轉就完成了。