题目要求: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 pre = head;
ListNode p = head.next;
ListNode next = null;
while(p!=null)
{
//先用next存放下一个节点
next = p.next;
//再把当前结点的后继指向前一个节点
p.next = pre;
//再把pre和p往后移
pre = p;
p = next;
}
//最后清除头节点的环
head.next=null;
return pre;
}
}
}