题目:
Reverse a singly linked list.
分析:
1. 反转后头结点的next为null。
2. 需要同时记录三个节点,分别是当前节点,它的前节点和next节点。
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 || head.next == null)
return head;
ListNode node = head;
ListNode pre = head.next;
node.next = null;
while(pre!=null)
{
ListNode temp = pre.next;
pre.next = node;
node = pre;
pre = temp;
}
return node;
}
}