前面咱们实现了几种常见的 链表 ,接下来,咱们来聊聊如何实现 单链表 的反转。html
示例:node
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Input: NULL
Output: NULL
复制代码
咱们能够经过循环遍历和递归这两种方式来实现链表的反转。git
定义三个指针,分别为prev、curr、next,而后遍历全部node结点,并移动这三个指针,改变curr结点的next指向,指向prev结点,实现linkedList的反转。github
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
ListNode next = null;
while(curr != null){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
head = prev;
return head;
}
}
复制代码
源码算法
其实递归的实现方式和前面循环的方式很是类似,前者是经过循环来移动指针,后者是经过递归来移动指针。bash
定义一个递归接口,传入curr与prev节点做为参数,内部再将curr的做为下次递归调用的prev入参,curr.next
做为下次递归调用的curr入参。数据结构
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode reverseList(ListNode head){
return reverseRecursively(head, null);
}
public ListNode reverseRecursively(ListNode curr, ListNode prev) {
if(curr == null){
return null;
}
if(curr.next == null){
ListNode head = curr;
curr.next = prev;
return head;
}
ListNode next1 = curr.next;
curr.next = prev;
ListNode head = reverseRecursively(next1, curr);
return head;
}
}
复制代码
源码spa
这两种方式的时间复杂度均为O(n),空间复杂度均为O(1)。3d