@Test
publicvoidtest_BubbleSort(){
ListNode listNode = new ListNode(8);
listNode.nextNode = new ListNode(4);
listNode.nextNode.nextNode = new ListNode(2);
listNode.nextNode.nextNode.nextNode = new ListNode(5);
BubbleSort bubbleSort = new BubbleSort();
ListNode head = bubbleSort.bubbleSort(listNode);
while (head!=null){
System.out.print(head.data+"->");
head = head.nextNode;
}
}
package com.struct.interview_question.list_interview_question.listsort;
publicclass QuickSort {
public ListNode quickSort(ListNode begin, ListNode end) {
if (begin == null || begin == end) {
returnbegin;
}
//找到基准点
ListNode index = divide(begin, end);
//对基准点前元素进行操作
quickSort(begin, index);
//对基准点后元素进行操作
quickSort(index.nextNode, end);
returnbegin;
}
publicstatic ListNode divide(ListNode begin, ListNode end) {
//没有元素或者只有一个元素if (begin == null || begin == end) {
returnbegin;
}
// 以头结点为基准对元素进行划分
int value = begin.data;
ListNode index = begin;
ListNode cur = begin.nextNode;
while(cur!=null){
if(cur.data<value){
index = index.nextNode;
//交换结点的值
int temp = cur.data;
cur.data = index.data;
index.data = temp;
}
cur = cur.nextNode;
}
//交换基准值和index结点的值begin.data = index.data;
index.data = value;
//返回基准值return index;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@Test
public void test_QuickSort(){
ListNode listNode = new ListNode(8);
listNode.nextNode = new ListNode(4);
listNode.nextNode.nextNode = new ListNode(2);
listNode.nextNode.nextNode.nextNode = new ListNode(5);
ListNode end = listNode.nextNode.nextNode.nextNode;
QuickSort quickSort = new QuickSort();
quickSort.quickSort(listNode,end);
ListNode head = quickSort.quickSort(listNode,end);
while (head!=null){
System.out.print(head.data+"->");
head = head.nextNode;
}
}
@Test
public void test_CombineTwoList(){
ListNode head1 = new ListNode(1);
ListNode head2 = new ListNode(2);
head1.nextNode = new ListNode(3);
head1.nextNode.nextNode = new ListNode(5);
head1.nextNode.nextNode.nextNode = new ListNode(7);
head2.nextNode = new ListNode(4);
head2.nextNode.nextNode = new ListNode(6);
head2.nextNode.nextNode.nextNode = new ListNode(8);
CombineTwoList combineTwoList = new CombineTwoList();
ListNode newNode = combineTwoList.combineList(head1,head2);
while (newNode!=null){
System.out.print(newNode.data+"->");
newNode = newNode.nextNode;
}
}