this is my first time asking here, I wanted to create a linked list while sorting it thanks

Posted by user2738718 on Stack Overflow See other posts from Stack Overflow or by user2738718
Published on 2013-11-02T21:50:57Z Indexed on 2013/11/02 21:53 UTC
Read the original article Hit count: 213

Filed under:
|
|
    package practise;
    public class Node {
            // node contains data and next

            public int data;
            public Node next;

            //constructor
            public Node (int data, Node next){
                this.data = data;
                this.next = next;
            }



            //list insert method
            public  void insert(Node list, int s){
                //case 1 if only one element in the list

                if(list.next == null && list.data > s)
                {
                    Node T = new Node(s,list);
                }
                else if(list.next == null && list.data < s)
                {
                    Node T = new Node(s,null);
                    list.next = T;
                }

                //case 2 if more than 1 element in the list
                // 3 elements present I set prev to null and curr to list               then performed while loop

                if(list.next.next != null)
                {
                    Node curr = list;
                    Node prev = null;
                    while(curr != null)
                    {
                        prev = curr;
                        curr = curr.next;
                        if(curr.data > s && prev.data < s){
                            Node T = new Node(s,curr);
                            prev.next = T;
                        }

                    }
                    // case 3 at the end checks for the data

                    if(prev.data < s){
                        Node T = new Node(s,null);
                        prev.next = T;
                    }

                }

            }


        }

// this is a hw problem, i created the insert method so i can check and place it in the correct order so my list is sorted

This is how far I got, please correct me if I am wrong, I keep inserting node in the main method, >Node root = new Node(); and root.insert() to add.

© Stack Overflow or respective owner

Related posts about java

Related posts about sorting