问题
反转一个单链表。 反转一个单链表。 示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
要求是本地反转。
分析
关键:需要记录原始工作指针的下一个节点。
代码
public ListNode reverseList(ListNode head) {
ListNode newHead = null;
ListNode p = head;
while (p != null) {
// 先记录next
ListNode next = p.next;
// 工作指针的next就可以赋新值
p.next = newHead;
newHead = p;
p = next;
}
return newHead;
}
update20210322
上面代码还是写的好!
update20220328
public ListNode reverseList(ListNode head) {
ListNode p = head;
ListNode next = null;
while (p != null) {
ListNode temp = p.next;
p.next = next;
next = p;
p = temp;
}
return next;
}
update20220328
public ListNode reverseList(ListNode head) {
ListNode p = head, pre = null;
while (p != null) {
ListNode temp = p.next;
p.next = pre;
pre = p;
p = temp;
}
return pre;
}
update 20220514
写了这么多,下面的才是正解!!
public ListNode reverseList(ListNode head) {
ListNode dummyHead = new ListNode();
ListNode p = head;
while (p != null) {
ListNode temp = p.next;
p.next = dummyHead.next;
dummyHead.next = p;
p = temp;
}
return dummyHead.next;
}
udpate 20220524
递归写法
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode rev = reverseList(head.next);
head.next.next = head;
head.next = null;
return rev;
}
硬广告
欢迎关注公众号:double6