輸入一個鏈表,反轉鏈表後,輸出鏈表的所有元素。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
//遞歸
/*
if(head==null || head.next==null)
return head;
ListNode p=ReverseList(head.next);
head.next.next=head;
head.next=null;
return p;
*/
//注意判斷是否爲空鏈表,以及是否只有一個元素的情況
if(head==null)
return null;
ListNode p=head;
ListNode q=p.next;
if(q==null)
return p;
ListNode r=q.next;
head.next=null;
q.next=p;
while(r!=null){
p=q;
q=r;
r=r.next;
q.next=p;
}
return q;
}
}