题目来源于 LeetCode 上第 206号(Reverse Linked List)问题,题目难度为 Easy,AC率55.2%面试
题目地址:https://leetcode.com/problems/reverse-linked-list/算法
Reverse a singly linked list.数组
反转一个单链表bash
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
复制代码
寻找递归结束条件:当链表只有一个节点,或者若是是空表的话,结束递归函数
head == null || head.next == null
复制代码
调用函数自己,传入下一个节点post
reverseList(head.next);
复制代码
咱们把 2->3->4->5 递归成了 5->4->3->2, 对于1节点没有去更改,因此1的next节点指向的是2,以下所示ui
递归前:
1 -> 2 -> 3 -> 4 -> 5
递归后:
1 -> 2 <- 3 <- 4 <- 5
|
v
null
复制代码
最后将节点 2 的 next 指向 1,而后把 1 的 next 指向 null,以下所示spa
null <- 1 <- 2 <- 3 <- 4 <- 5
复制代码
算法效率以下图所示: 3d
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode nextNode = reverseList(head.next);
ListNode tempNode = head.next;
tempNode.next = head;
head.next = null;
return nextNode;
}
}
复制代码
设置三个节点 preNode, head, nextcode
算法效率以下图所示:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode preNode = null;
while (head!=null){
ListNode next = head.next;
head.next = preNode;
preNode = head;
head = next;
}
return preNode;
}
}
复制代码
算法效率以下图所示:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode newHead = new ListNode(0);
while (head!=null){
ListNode tempNode = new ListNode(head.val);
tempNode.next = newHead.next;
newHead.next = tempNode;
head = head.next;
}
return newHead.next;
}
}
复制代码