反转一个单链表:
/**
* 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(null == head || null == head.next) {
return head;
}
ListNode pre = head;
ListNode p = pre.next;
ListNode next = null;
while(p != null) {
next = p.next;
p.next = pre;
pre = p;
p = next;
}
head.next = null;
return pre;
}
}