左程云_算法与数据结构 — 链表问题 — 04反转单向和双向链表
2017-06-26 01:26
716 查看
问题描述
实现反转链表的方法,要求时间复杂度为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)); }
}
实现结果
问题总结
题目不难,要利用已经有的结构来进行完善;相关文章推荐
- 左程云_算法与数据结构 — 链表问题 — 05反转部分单链表
- 链表问题——反转单向链表和双向链表
- [算法]反转单向链表和双向链表
- 链表问题---反转单向和双向链表
- 数据结构 反转单向链表和双向链表
- 《算法之美》の链表问题の单向链表的反转
- 数据结构 04 链表 双向链表
- 算法与数据结构面试题(7)-链表“香蕉”问题
- 算法学习笔记(二)----几个算法题,包括链表中的环,单词反转等问题
- 数据结构之链表与数组(二) -单向链表上的简单操作问题
- 【数据结构】单向链表,单向循环链表,双向循环链表
- 算法与数据结构之四----双向链表
- 《Delphi 算法与数据结构》学习与感悟[8]: 单向链表的添加、删除与遍历
- 算法与数据结构面试题(1)-把二元查找树转变成排序的双向链表
- 线性表16:双向链表 - 数据结构和算法21
- 《Delphi 算法与数据结构》学习与感悟[10]: 双向链表
- C++类模板 实现双向循环链表的基本算法 《数据结构》(C++版 北京科海)中摘抄
- 线性表16:双向链表 - 数据结构和算法21
- 数据结构基本算法:单向链表
- 数据结构-【链表】单向链表的逆置和双向循环链表