单链表冒泡排序
来源:互联网 发布:好搜排名优化软件 编辑:程序博客网 时间:2024/05/21 10:40
一. 题目
如题.
代码请到我的代码库中下载 Point2Offer
二. 代码
package week_4;/** * 单链表冒泡排序 * @author dingding * Date :2017-7-3 12:25 */public class SortLink { public static void main(String[] args) { test1(); test2(); test3(); test4(); } //solution,冒泡排序,直接交换两个值,关键在于循环条件 private static Node Sort(Node head){ if (head == null) { return null; } if (head.next == null) { return head; } Node tail = null; Node cur = null; cur = head; while(cur != tail){ while (cur.next != tail){ if (cur.value>cur.next.value) { int temp = cur.value; cur.value = cur.next.value; cur.next.value = temp; } cur = cur.next; } tail = cur; //不等于最后一个数 cur = head; //第二轮head为4 } return head; } //打印链表 private static void printLink(Node head){ if (head == null) { System.out.println("Invalid input."); return; } while (head != null){ System.out.print(head.value+" "); head = head.next; } System.out.println(); } /*======================测试用例===============*/ private static void test1() { Node first = new Node(5); Node second = new Node(4); Node third = new Node(3); Node fourth = new Node(2); Node fifth = new Node(1); first.next = second; second.next = third; third.next = fourth; fourth.next = fifth; Node head = Sort(first); printLink(head); } private static void test2() { Node first = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(2); Node fifth = new Node(6); first.next = second; second.next = third; third.next = fourth; fourth.next = fifth; Node head = Sort(first); printLink(head); } private static void test3() { Node first = new Node(1); Node head = Sort(first); printLink(head); } private static void test4() { Node head = Sort(null); printLink(null); }}//定义一个链表class Node{ int value; Node next; public Node(int value){ this.value = value; this.next = null; }}
有不妥当之处,麻烦告知:D
阅读全文
0 0
- 单链表排序(冒泡排序)
- 单链表冒泡排序与数组冒泡排序
- 单链表排序之冒泡排序
- 单链表的冒泡排序
- 单链表排序--冒泡法
- 单链表实现冒泡排序
- 单链表的冒泡排序
- 单链表冒泡排序
- 单链表排序-冒泡
- 单链表实现冒泡排序
- 单链表实现冒泡排序
- 单链表之冒泡排序
- 单链表冒泡排序
- 单链表冒泡排序
- 单链表的冒泡排序
- 单链表冒泡排序
- 单链表冒泡排序
- 单链表的冒泡排序
- 使用Spring StateMachine框架实现状态机
- 架构师之路(十七)Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)
- select标签使用 三目运算符
- 关于安卓是怎么联网的,或者说是怎么连接服务器的
- 中文输入纠错任务整理
- 单链表冒泡排序
- 居中
- iptables-ssh-links
- 第三章:Javascript类型、值和变量。
- Oracle包和包体以及与非包体定义函数、过程的区别
- java分页三个类 PageBean ResponseUtil StringUtil
- Go并发编程
- http状态码
- 51nod1301 集合异或和