简体   繁体   中英

Insert a node at a specific position in a linked list JAVA

public static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode llist, int data, int position) {
    if(llist == null) {
        llist =  new SinglyLinkedListNode(data);
        return llist;
    } else {
        for (int i = 0; i < position-1; i++) {
            llist = llist.next;
        }
        SinglyLinkedListNode temp = llist;
        llist.next = new SinglyLinkedListNode(data);
        llist = llist.next;
        llist.next = temp.next;         
        return llist;
    }
}

This is my code to place a custom index node in LinkedList. But hackerrank is not accepting my code. What's wrong with my algorithm?

The problem is that your code always returns the newly created node, but you should always return the first<\/em> node in the list, which either is what it was when you got it, or is the new node in case the position was zero.

<\/h3>

I'll not provide the corrected code, but will give you two hints:

Easiest solution No need of explaination : Solution :

static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode head, int data, int position) {
        if (head == null) return null;
        SinglyLinkedListNode temp = new SinglyLinkedListNode(data);
        if (position == 0) {
            temp.next = head;
            return temp;
        }
        SinglyLinkedListNode p = head;
        for (int i = 0; i< position-1; i++) {
            p = p.next;
        }
        SinglyLinkedListNode next = p.next;
        p.next = temp;
        temp.next = next;
        return head;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM