Reverse a singly linked list.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null)
return head;
else{
ListNode p=head.next;
ListNode q=p.next;
ListNode tail=head;
tail.next=null;
while(q!=null){
p.next=tail;
tail=p;
p=q;
q=q.next;
}
p.next=tail;
return p;
}
}
}