Reverse a singly linked list.
思路:新建链表,将原来链表元素一次取出放在新链表的头部的后面,返回新链表头.next
</pre><pre name="code" class="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 p = head;
ListNode res = new ListNode(0);
ListNode restemp = null;
while (p != null) {
restemp = res.next;
res.next = p;
p = p.next;
res.next.next = restemp;
}
return res.next;
}
}