206. 反转链表
2020-09-25 本文已影响0人
伶俐ll
题目链接
题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
代码实现
- 递归实现
public static ListNode reverseList(ListNode head) {
// 如果第一次传进来的head != null,并且head.next != null,那么第一次执行这句代码返回的head就是newHead,即倒数第一个head
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
// 第一次执行这句代码的head是倒数第二个head
// 让最后一个head的next执行倒数第二个,倒数第二个head的next指向null
// 之后每次来到这句代码,拿到的head都是前一个head
head.next.next = head;
head.next = null;
return newHead;
}
- 迭代实现
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
// 上一个节点
ListNode preNode = null;
while(head != null){
// 下一个节点
ListNode nextNode = head.next;
// 当前节点的next指针指向下一个节点
head.next = preNode;
// 使当前节点成为上一个节点
preNode = head;
// 使下一个节点成为当前节点
head = nextNode;
}
// 当head == null的时候,preNode就是最后一个节点,也就是反转之后的头节点
return preNode;
}
}