Java
/**
* 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) return head;
ListNode pre=null;
ListNode cur=head;
ListNode nt=head.next;
while(cur.next!=null)
{
nt=cur.next;
cur.next=pre;
pre=cur;
cur=nt;
}
cur.next=pre;
head=cur;
return head;
}
}
Javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
if(head===null) return head;
var pre=null;
var cur=head;
var nt=head.next;
while(cur.next!==null)
{
nt=cur.next;
cur.next=pre;
pre=cur;
cur=nt;
}
cur.next=pre;
head=cur;
return head;
};
优解,差不多
注意头节点的指针要指向空