Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Node {
- //content of each node
- public int data;
- //pointer to the next Node in the list
- public Node next;
- public Node (int data){
- this.data = data;
- }
- //prints out the data in the Node
- public void display(){
- System.out.print(data);
- }
- public String toString(){
- return data + "";
- }
- }
- public class LinkedList {
- //a pointer to the latest value in the list
- public Node firstNode;
- //the number of nodes in the list
- public int numberOfNodes;
- //starts at a null value
- LinkedList(){
- firstNode = null;
- }
- //check if the list is empty
- public boolean isEmpty(){
- return(firstNode == null);
- }
- //add a new node
- public void add(int data){
- Node n = new Node(data); //new node
- n.next = firstNode; //n.next gets the address to the previous node
- firstNode = n; //firstNode point at the new node n
- }
- //cycle through the nodes
- public void display(){
- Node n = firstNode;
- while(n != null){
- n.display();
- //System.out.println("Next node: " + n.next);
- n = n.next;
- numberOfNodes++;
- }
- }
- public void bubblesort(LinkedList list, int number){
- boolean swapped = true;
- while(number > 0 && swapped){
- swapped = false;
- Node n1 = list.firstNode;
- Node n2 = n1.next;
- for (int i = 0; i < number - 1; i++) {
- if(n1.data > n2.data){
- swapped = true;
- swap(list, n1, n2);
- }
- n1 = n1.next;
- n2 = n1.next;
- }
- }
- }
- static void swap(LinkedList List, Node n1, Node n2)
- {
- int n = n1.data;
- n1.data = n2.data;
- n2.data = n;
- }
- }
- public class Driver {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- LinkedList list = new LinkedList();
- list.add(2);
- list.add(8);
- list.add(3);
- list.add(9);
- list.add(5);
- list.add(6);
- list.display();
- System.out.println();
- list.bubblesort(list, list.numberOfNodes);
- list.display();
- //System.out.println(list.numberOfNodes);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement