How to insert an item at a given position in a linked list?

后端 未结 7 1351
天命终不由人
天命终不由人 2021-01-21 12:50

This how you would add an item:

public void insert (Object item)
{
    Link add = new Link();
    add.data = item;
    add.next = head;
    _head = add;
    ++_l         


        
7条回答
  •  时光说笑
    2021-01-21 13:18

    You need a temporary variable that start from the head, traverse each node until the desired position or the end of the list, then insert the new node.

    Since it is a homework exercise, I will only post pseudo code:

    if pos < 0
        //define what to do here...
        return
    end if
    if pos == 0 
        //inserting at the beginning
        insert(item)
        return
    end if
    Link temp <- head
    int index <- 0
    while index < pos and temp->next != null
        temp <- temp->next
        index <- index + 1
    end while
    //now you're at your desired location or at the end of the list
    Link newLink <- new Link
    newLink->data <- item
    newLink->next <- temp->next
    temp->next <- newLink
    

提交回复
热议问题