題目描述:
輸入一個鏈表,反轉鏈表后,輸出新鏈表的表頭。
解題思路:
本題比較簡單,有兩種方法可以實現:(1)三指針。使用三個指針,分別指向當前遍歷到的結點、它的前一個結點以及后一個結點。將指針反轉后,三個結點依次前移即可。(2)遞歸方法。同樣可以采用遞歸來實現反轉。將頭結點之后的鏈表反轉后,再將頭結點接到尾部即可。
編程實現(Java):
//方法一:三指針
public ListNode ReverseList(ListNode head) {
if(head==null)
return null;
ListNode first=null;
ListNode second=head;
ListNode third=head.next;
while(third!=null){
second.next=first; //三指針之間的變換
first=second;
second=third;
third=third.next;
}
second.next=first;
return second;
}
//方法二:遞歸
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode temp=ReverseList(head.next);
head.next.next=head;
head.next=null;
return temp;
}