Skip to content

Instantly share code, notes, and snippets.

@desaiuditd
Last active January 23, 2016 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save desaiuditd/7ff17b428f493cbe1a0d to your computer and use it in GitHub Desktop.
Save desaiuditd/7ff17b428f493cbe1a0d to your computer and use it in GitHub Desktop.
Sort Linked List
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sortll;
/**
*
* @author Pooja
*/
class LinkedList
{
class Node
{
Node next;
int data;
public Node(int data)
{
this.data=data;
next=null;
}
}
Node head;
public LinkedList() {
this.head = null;
}
public void insertFirst(int data)
{
Node newNode = new Node(data);
head=newNode;
}
public void insertEnd(int data)
{
Node temp=head;
Node newNode = new Node(data);
if(head==null)
{
head= newNode;
return;
}
while(temp.next!=null) {
temp = temp.next;
}
temp.next=newNode;
}
public void display() {
Node temp = head;
while(temp!=null) {
System.out.println(temp.data);
temp = temp.next;
}
}
public void sort()
{
Node temp=head;
while(temp!=null)
{
Node ptr = temp.next;
while(ptr!=null)
{
if(temp.data>ptr.data)
{
int swap=ptr.data;
ptr.data=temp.data;
temp.data=swap;
}
ptr=ptr.next;
}
temp=temp.next;
}
}
}
public class SortLL {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
LinkedList l1= new LinkedList();
//LinkedList1 l2 = new LinkedList1();
System.out.println("First LinkedList");
l1.insertFirst(5);
l1.insertEnd(6);
l1.insertEnd(3);
l1.insertEnd(1);
l1.display();
l1.sort();
l1.display();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment