Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

java - How to make a linked list sorted?

Write a java method in your Linked List Project to perform the sorted insertion in your Linked List. Sorted insertion is one in which, whenever you insert a new element, it is inserted on its sorted location. but I'm not getting the output here is my code.

{
  public void insertSorted(int data) 
{
    
    Node temp = new Node(data);
    if(head == null || head.Data > data) 
    {
        temp.next = head;
        head = temp;
    }
    Node head2 = head;
    while(head2.next != null && head2.next.Data < data) 
    {
        head2 = head2.next;
    }
    temp.next = head.next;
    head.next = temp;
}

public void Display() 
{
    Node t = head;
    while(t != null)
    {
        System.out.print(t.Data+" -> ");
        t = t.next;
    }
    System.out.println("NULL");
}
}
question from:https://stackoverflow.com/questions/65868839/how-to-make-a-linked-list-sorted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try this one it will work as you expected ->

 public void seprator1(Node curr) {
    if (curr == null || curr.next == null) {
        return;
    }

    Node Even, EvenTail, oddStartingNode, oddEndNode;

    Even = EvenTail = oddStartingNode = oddEndNode = null;

    while (curr != null) {
        if (curr.data % 2 == 0) {
            if (Even == null) {
                Even = curr;
                EvenTail = Even;
            } else {
                EvenTail.next = curr;
                EvenTail = EvenTail.next;
            }
        } else {
            if (oddStartingNode == null) {
                oddStartingNode = curr;
                oddEndNode = oddStartingNode;
            } else {
                oddEndNode.next = curr;
                oddEndNode = oddEndNode.next;
            }
        }

        curr = curr.next;
    }

    displayNode(Even);
    System.out.println();
    displayNode(oddStartingNode);

}

private void displayNode(Node node) {
    if (node == null) {
        return;
    }
    System.out.print(node.data+" ");
    displayNode(node.next);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...