问题描述
实现反转链表的方法,要求时间复杂度为O(N),空间复杂度为O(1)
思路分析
- 利用桟来实现反转:时间复杂度O(N),空间复杂度O(N);
将链表推入桟内,然后出桟构成新的链表; - 原地反转,利用其他的一些变量来进行转换:时间复杂度O(N)空间复杂度O(1)。
代码实现
package algorithm_zuochengyun;
public class CH2_04_reverseList {
// 给定一个单向链表头结点head,将链表反转
public static Node reverseList(Node head) {
Node pre = null;
Node next = null;
if (head == null || head.next == null) {
return head;
}
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static Node getReverseListFirst(Node head, int n) {
// 假设123456789 从1翻转到5即可得 543216789
// 此方法返回5这个结点,node(1).next = null;
Node pre = null;
Node next = null;
if (head == null || head.next == null) {
return head;
}
while (n-- > 0) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static Node getReverseListRest_First(Node head, int n) {
// 假设123456789 从1翻转到5即可得 543216789
// 此方法返回6这个结点
Node pre = null;
Node next = null;
if (head == null || head.next == null) {
return head;
}
while (n-- > 0) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return next;
}
public static DoubleNode reverseList(DoubleNode head) {
if (head == null || head.next == null) {
return head;
}
DoubleNode last = null;
DoubleNode next = null;
DoubleNode cur = head;
DoubleNode temp = null;
while (cur != null) {
next = cur.next;
cur.next = last;
last = cur.last;
cur.last = next;
last = cur;
cur = next;
}
return last;
}
public static void main(String[] args) {
Node head = Node.init();
Node.Print(head);
// Node.Print(reverseList(head));
Node.Print(getReverseListFirst(head, 7));
DoubleNode head1 = DoubleNode.init();
DoubleNode.PrintNext(head1);
DoubleNode.PrintNext(reverseList(head1));
}
}
实现结果
问题总结
题目不难,要利用已经有的结构来进行完善;