反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
1、多画图理解会容易点。这个迭代法更简单些容易想。但是递归的更好理解,易读性略胜一筹。
2、递归,时间复杂度 O(n), 空间复杂度O(n)
迭代,时间复杂度 O(n), 空间复杂度O(1)
package com.data;
public class SolutionReverse {
public static void main(String[] args) {
// TODO Auto-generated method stub
SolutionReverse plus = new SolutionReverse();
ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4, new ListNode(5))));
ListNode node = plus.reverseList(l2);
while (node != null) {
System.out.print(node.val + "--");
node = node.next;
}
System.out.println();
l2 = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6))))));
node = plus.reverseList(l2);
while (node != null) {
System.out.print(node.val + "--");
node = node.next;
}
}
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newNode = reverseList(head.next);
head.next.next = head;
head.next = null;
return newNode;
}
public ListNode reverseList3(ListNode head) {
ListNode parent = null;// 头结点他爹是空值
ListNode son = head;// 头结点做起始节点当儿子遍历
while (son != null) {
ListNode sonson = son.next;// 儿子的儿子就是孙子
son.next = parent;// 儿子指向他爹
parent = son;// 儿子当爹
son = sonson;// 孙子当儿子
}
return parent;// 反转后的头结点应该是son的爹
}
public ListNode reverseList2(ListNode head) {
ListNode parent = head;
ListNode son = head.next;
head.next = null;
while (son != null) {
ListNode sonson = son.next;
son.next = parent;
parent = son;
son = sonson;
}
return parent;
}
static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。