先上代码:
// 思路一
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode newHead = new ListNode(0);
ListNode temp = head;
ListNode nxt = null;
while (temp != null) {
nxt = temp.next;
temp.next = newHead.next;
newHead.next = temp;
temp = nxt;
}
return newHead.next;
}
} 这道题,个人认为有那么点小漏洞。题中并没有说明给出的链表是否有头节点。不过根据题目的检测结果可知,题中的链表是没有头节点的,也就是说题中的head形参,其实代表了链表的第一个元素,而不是链表的头节点。
我目前有两种思路,一种需要用到2个辅助指针,另一种需要用到3个辅助指针。
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode prev = head;
ListNode curr = head.next;
ListNode nxt = curr.next;
head.next = null;
while (curr != null) {
head = curr;
curr.next = prev;
prev = curr;
curr = nxt;
if (nxt != null) nxt = nxt.next;
}
return head;
}
} 
京公网安备 11010502036488号