Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

Sort elements using operations using linked List.

 class LLNode

    {

        constructor(data)

        {

            this.data=data;

            this.next=null;

        }

    }

class LinkedList

    {

        constructor(data)

        {

            this.head=null;

            this.tail=null;

        }

 

        create(data)

        {

            const newNode = new LLNode(data);

            if(this.head==null)

            {

                this.head=newNode;

                this.tail=newNode;

            }

            else

            {

                let current=this.head;

                while(current.next!=null)

                    {

                        current=current.next;

                       

                    }

                current.next=newNode;

            }

        }

sort() {

    if (this.head === null) {

      return;

    }

    let swapped = false;

    do {

      swapped = false;

      let current = this.head;

      while (current.next !== null) {

        if (current.data > current.next.data) {

          const temp = current.data;

          current.data = current.next.data;

          current.next.data = temp;

          swapped = true;

        }

        current = current.next;

      }

    } while (swapped);

  }

 

        display()

        {

            let current=this.head;

            if(current==null)

            {

                console.log("LIst is empty");

            }

            else

            {

                while(current!=null)

                    {

                      console.log(current.data);

                     current=current.next;

                    }

               

            }

        }

}

 

const list=new LinkedList();

list.create(40);

list.create(20);

list.create(60);

list.create(100);

list.create(10);

console.log("Before Sort:");

list.display();

list.sort();

console.log("After Sort:");

list.display();

 

 

Output:

Before Sort:

40

20

60

100

10

After Sort:

10

20

40

60

100

Post a Comment

0 Comments

Ad Code

Responsive Advertisement