Skip to content

Commit 47d373f

Browse files
Added LinkedListSort.Java
Adding a sort linked list function that takes in the head of the linked list and returns the list, as described in open issue: TheAlgorithms#2450.
1 parent e4fa83b commit 47d373f

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
//Author: Vicente Cortes
2+
//Github: https://github.com/vicentecortes23
3+
4+
//https://en.wikipedia.org/wiki/Bubble_sort
5+
//This java program sorts a LinkedList given a head pointer, as described in the issue https://github.com/TheAlgorithms/Java/issues/2450.
6+
package com.thealgorithms.sorts;
7+
8+
9+
public class LinkedListSort {
10+
11+
public static class Node {
12+
int value;
13+
Node next;
14+
Node prev;
15+
16+
public Node(int val)
17+
{
18+
this.value = val;
19+
this.next = null;
20+
this.prev = null;
21+
}
22+
23+
public void push(int val){
24+
25+
Node newNode = new Node(val);
26+
27+
Node currentNode = this;
28+
29+
while(currentNode.next != null){
30+
currentNode = currentNode.next;
31+
}
32+
33+
currentNode.next = newNode;
34+
newNode.prev = currentNode;
35+
}
36+
37+
}
38+
39+
public Node sortList(Node node){
40+
41+
//in order to sort these two lists, we will use bubble sort starting from the head node.
42+
Node thisNode = node;
43+
Node nextNode = null;
44+
45+
while(thisNode != null){
46+
47+
nextNode = thisNode.next;
48+
49+
while(nextNode != null){
50+
51+
if (thisNode.value > nextNode.value){
52+
int temp = thisNode.value;
53+
thisNode.value = nextNode.value;
54+
nextNode.value = temp;
55+
}
56+
57+
nextNode = nextNode.next;
58+
59+
}
60+
thisNode = thisNode.next;
61+
}
62+
63+
return node;
64+
}
65+
66+
public static void main(String args[]){
67+
68+
LinkedListSort sorter = new LinkedListSort();
69+
70+
Node head = new Node(5);
71+
head.push(3);
72+
head.push(6);
73+
head.push(7);
74+
head.push(1);
75+
head.push(2);
76+
head.push(8);
77+
head.push(4);
78+
79+
head = sorter.sortList(head);
80+
81+
while(head != null){
82+
System.out.print(head.value + " ");
83+
head = head.next;
84+
}
85+
}
86+
};

0 commit comments

Comments
 (0)