insertion sort list
来源:互联网 发布:知乎 中国铁路 非洲 编辑:程序博客网 时间:2024/05/03 23:18
public class Insert2 {
/**
* @param args
*/
public static ListNode insertionSortList(ListNode head) {
// q是外层循环,p是内层循环
if(head==null||head.next==null){
return head;
}
ListNode before = new ListNode(-1);
while (head != null) {
ListNode q = head;
head = head.next;
ListNode p=before;
while (p.next != null && p.next.val < q.val) {
p = p.next;
}
if (p.next == null) {
p.next = q;
q.next = null;
} else {
q.next = p.next;
p.next = q;
}
}
return before.next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode head = new ListNode(4);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(6);
ListNode n4 = new ListNode(3);
ListNode n5 = new ListNode(1);
head.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = null;
// InsertionSortList kInsertionSortList = new InsertionSortList();
ListNode ret = insertionSortList(head);
while (ret != null) {
System.out.println(ret.val);
ret = ret.next;
}
}
/**
* @param args
*/
public static ListNode insertionSortList(ListNode head) {
// q是外层循环,p是内层循环
if(head==null||head.next==null){
return head;
}
ListNode before = new ListNode(-1);
while (head != null) {
ListNode q = head;
head = head.next;
ListNode p=before;
while (p.next != null && p.next.val < q.val) {
p = p.next;
}
if (p.next == null) {
p.next = q;
q.next = null;
} else {
q.next = p.next;
p.next = q;
}
}
return before.next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode head = new ListNode(4);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(6);
ListNode n4 = new ListNode(3);
ListNode n5 = new ListNode(1);
head.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = null;
// InsertionSortList kInsertionSortList = new InsertionSortList();
ListNode ret = insertionSortList(head);
while (ret != null) {
System.out.println(ret.val);
ret = ret.next;
}
}
}
创建一个新的头结点before,从head中挨个往before 中添加。head指针用于挨个遍历原链表,并将各个节点给q,p节点用于与q进行比较,使得q可以插入在before中合适的位置。
0 0
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List
- Leetcode: Insertion Sort List
- [LeeCode] Insertion Sort List
- leetcode-Insertion Sort List
- [LeetCode]Insertion Sort List
- Insertion Sort List
- 【LeetCode】Insertion Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- [LeetCode] Insertion Sort List
- list - insertion sort - AC
- cocos2d-x游戏实例(22)-纵版射击游戏(9)
- 学习shell脚本之前的基础知识
- 白鹭时代到底怎么样有前途么
- ROS探索总结(一)——ROS简介
- 网络负载介绍以及配置windows网络负载
- insertion sort list
- 二叉树的创建以及二叉树的4种遍历方法
- RandomStringUtils产生随机数
- MySQL 登录问题
- CentOS7 LNMP一键安装
- java.util.concurrent lock对象 lock()和tryLock()
- C++学习笔记 容器
- poj 1743 Musical Theme(后缀数组)
- 2012年5月SAT香港真题解析