单链表逆序(三种方式)
2016-05-20 19:09
519 查看
三种方式实现单链表的逆序,分别是头结点插入,对称交换和利用堆栈来实现。三种方式分别是出于空间和时间的考虑来实现的,详见注释。
public class LinkedList { class Node { private Node next; private Object data; public Node() { super(); } public Node(Object data, Node next) { this.data = data; this.next = next; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } } private Node head; public Node first() { return head.next; } public Node tail() { Node temp = head; while (temp.next != null) temp = temp.next; return temp; } public Node head() { return head; } public LinkedList() { head = new Node(null, null); } public boolean addStack(Object data, Node head) { boolean flag = false; Node node = new Node(data, null); if (!flag) { node.next = head.next; head.next = node; flag = true; } return flag; } public boolean addQueue(Object data, Node head) { Node temp = head; while (temp.next != null) temp = temp.next; boolean flag = false; Node node = new Node(data, null); if (!flag) { temp.next = node; flag = true; } return flag; } public void print(Node head) { Node temp = head; while (temp.next != null) { System.out.println("list node data :" + temp.data); temp = temp.next; } System.out.println("list node data :" + temp.data); } public void addQueue() { } //直接头结点插入 public LinkedList invertedList(Node head) { LinkedList newList = new LinkedList(); Node temp = head; while (temp.next != null) { addStack(temp.data, newList.head); temp = temp.next; } addStack(temp.data, newList.head); return newList; } public int length() { Node temp = head; int i = 0; while (temp.next != null) { i++; temp = temp.next; } return i; } //交换两个对应的数据来实现,链表逆序 public void invertedListExchange(Node head) { Node tempStart = head; Object old = null; Node tempEnd = null; int halfLen = this.length() / 2; for (int i = 0; i < halfLen; i++) { tempEnd = tempStart; if (i == 0) { tempEnd = this.tail(); } while (i != 0 && tempEnd.next.data != old) tempEnd = tempEnd.next; System.out.println(tempStart.data); Object tt = tempStart.data; tempStart.data = tempEnd.data; tempEnd.data = tt; old = tempEnd.data; tempStart = tempStart.next; } } //利用栈的性质来实现 public LinkedList invertedListByStack(Node head) { Deque<Object> stack = new java.util.LinkedList<Object>(); Node temp = head; while (temp.next != null) { stack.push(temp.data); temp = temp.next; } stack.push(temp.data); LinkedList newList = new LinkedList(); Node node = newList.head; while (!stack.isEmpty()) { addQueue(stack.pop(), node); } return newList; } }
相关文章推荐
- 用RadASM 开发窗口程序
- MyBatis逆向工程自动生成实体类和映射文件
- 流量统计
- 顺序表应用1:多余元素删除之移位算法
- Hibernate常见问题
- 对象
- 比较两个字符串【不可以使用strcmp】
- Azure手把手系列 1:微软中国公有云概述 推荐
- CentOS 7安装Nexus,搭建Maven私服
- c++模版应用实例
- centos mysql自动备份脚本
- 水王练习1
- js中sort()方法的用法,参数以及排序原理
- 练习三1015
- 操作系统的信号量和管程
- struts2中的There is no Action mapped for namespace [/] 错误
- 屏蔽PHP默认设置中的Notice警告的方法
- TIME_WAIT状态
- 课堂作业
- 傲慢是把并购导向失败的最大理由