题目原文:

Shuffling a linked list. Given a singly-linked list containing n items, rearrange the items uniformly at random. Your algorithm should consume a logarithmic (or constant) amount of extra memory and run in time proportional to nlogn in the worst case.

分析:

此题要求对单向链表进行随机排序,可以考虑先实现个链表的归并排序(见我的另一篇文章),再改造成这里的随机排序。

 import java.util.Iterator;
import edu.princeton.cs.algs4.StdRandom;
/**
/**
* 对单向链表的随机归并排序
* @author evasean www.cnblogs.com/evasean/
* @param <T>
*/
public class ShuffleLinkedList<T extends Comparable<T>> implements Iterable<T>{
private Node first = null;
private Node last = null;
private int n;
private class Node{
T element;
Node next;
}
private boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
@Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return new ListIterator();
}
private class ListIterator implements Iterator<T>{
private Node current = first;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return current != null;
} @Override
public T next() {
// TODO Auto-generated method stub
T t = current.element;
current = current.next;
return t;
}
}
public void add(T t){
Node node = new Node();
node.element = t;
node.next = null;
if(first == null && last == null){
first = node;
last = node;
}else if(first != null && first == last){
first.next = node;
last = node;
}else{
last.next = node;
last = node;
}
n++;
}
@Override
public String toString(){
Iterator<T> iter = iterator();
String ret = iter.next().toString();
while(iter.hasNext()){
ret += ", "+ iter.next().toString() ;
}
return ret;
}
public void mergeSort(){
first = sort(first);
} private Node sort(Node head){
if(head == null || head.next == null) return head;
Node slow = head;
Node fast = head;
//取中间节点
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
Node left = head;
Node right = slow.next;
slow.next = null; //将左右链表分开
left = sort(left);
right = sort(right);
return merge(left,right);
}
private Node merge(Node left, Node right){
//System.out.println("left="+left.element+",right="+right.element);
Node aux = new Node(); //需要耗费logn的额外空间
Node l= left;
Node r = right;
Node current = aux;
while(l != null && r!=null){
int rand = StdRandom.uniform(2);
if(rand == 0){ //如果随机数选为0,则从左侧选取元素
current.next = l;
current = current.next;
l= l.next;
}else{ //如果随机数选为1,则从右侧选取元素
current.next = r;
current = current.next;
r = r.next;
}
}
if(l!=null) current.next = l; // 如果左侧没遍历完,将其连接至current后
else if(r != null) current.next = r; //如果右侧没遍历完,将其连接至current后
return aux.next; //返回归并好的链表
}
public static void main(String[] args){
ShuffleLinkedList<Integer> sll = new ShuffleLinkedList<Integer>();
sll.add(1);
sll.add(2);
sll.add(11);
sll.add(9);
sll.add(10);
sll.add(4);
sll.add(7);
System.out.println(sll);
sll.mergeSort();
System.out.println(sll);
} }

Coursera Algorithms week3 归并排序 练习测验: Shuffling a linked list的更多相关文章

  1. Coursera Algorithms week3 归并排序 练习测验: Counting inversions

    题目原文: An inversion in an array a[] is a pair of entries a[i] and a[j] such that i<j but a[i]>a ...

  2. Coursera Algorithms week3 归并排序 练习测验: Merging with smaller auxiliary array

    题目原文: Suppose that the subarray a[0] to a[n-1] is sorted and the subarray a[n] to a[2*n-1] is sorted ...

  3. Coursera Algorithms week3 快速排序 练习测验: Selection in two sorted arrays(从两个有序数组中寻找第K大元素)

    题目原文 Selection in two sorted arrays. Given two sorted arrays a[] and b[], of sizes n1 and n2, respec ...

  4. Coursera Algorithms week3 快速排序 练习测验: Decimal dominants(寻找出现次数大于n/10的元素)

    题目原文: Decimal dominants. Given an array with n keys, design an algorithm to find all values that occ ...

  5. Coursera Algorithms week3 快速排序 练习测验: Nuts and bolts

    题目原文: Nuts and bolts. A disorganized carpenter has a mixed pile of n nuts and n bolts. The goal is t ...

  6. Coursera Algorithms week1 算法分析 练习测验: Egg drop 扔鸡蛋问题

    题目原文: Suppose that you have an n-story building (with floors 1 through n) and plenty of eggs. An egg ...

  7. Coursera Algorithms week1 算法分析 练习测验: 3Sum in quadratic time

    题目要求: Design an algorithm for the 3-SUM problem that takes time proportional to n2 in the worst case ...

  8. Coursera Algorithms week2 基础排序 练习测验: Dutch national flag 荷兰国旗问题算法

    第二周课程的Elementray Sorts部分练习测验Interview Questions的第3题荷兰国旗问题很有意思.题目的原文描述如下: Dutch national flag. Given ...

  9. Coursera Algorithms week4 基础标签表 练习测验:Inorder traversal with constant extra space

    题目原文: Design an algorithm to perform an inorder traversal of a binary search tree using only a const ...

随机推荐

  1. (转)Hadoop入门进阶课程

    http://blog.csdn.net/yirenboy/article/details/46800855 1.Hadoop介绍 1.1Hadoop简介 Apache Hadoop软件库是一个框架, ...

  2. jquery from使用

    jquery form是一个基于jquery的表单异步提交的插件,通过它能快速简便的提交表单. html <div> <form id="ajaxForm" me ...

  3. java同学毕业后学习之路建议

    第一部分:对于尚未做过Java工作的同学,包括一些在校生以及刚准备转行Java的同学. 滤过: 第二部分:对于参加工作一年以内的同学. 恭喜你,这个时候,你已经拥有了一份Java的工作.这个阶段是你成 ...

  4. linux获得网卡信息

    #define MAX_INTERFACE 64 int showifs() { int i; int rc; int sock; int ifnum; struct ifreq ifr[MAX_IN ...

  5. 51nod1103 N的倍数

    [题解] 先预处理出模N意义下的前缀和sum[i]. 1.如果sum[i]=0,那么1~i的数之和就是N的倍数 2.sum[i]%N总共有0~N-1这N种情况:根据1,如果sum[i]为0则必定有解: ...

  6. Vue 安装教程

    1.下载node.js https://nodejs.org/en/ 2.检查环境变量: npm init (初始化项目) npm i webpack vue vue-loader 安装依赖: npm ...

  7. 【LeetCode Weekly Contest 26 Q1】Longest Uncommon Subsequence I

    [题目链接]:https://leetcode.com/contest/leetcode-weekly-contest-26/problems/longest-uncommon-subsequence ...

  8. 【codeforces 785E】Anton and Permutation

    [题目链接]:http://codeforces.com/problemset/problem/785/E [题意] 给你一个初始序列1..n顺序 然后每次让你交换任意两个位置上面的数字; 让你实时输 ...

  9. Spring Boot 内嵌容器 Tomcat / Undertow / Jetty 优雅停机实现

    Spring Boot 内嵌容器 Tomcat / Undertow / Jetty 优雅停机实现 Anoyi 精讲JAVA 精讲JAVA 微信号 toooooooozi 功能介绍 讲解java深层次 ...

  10. Aggressive Cows 二分

    Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are locat ...