Inserting a node into a linked list in constant-time?

前端 未结 7 985
别跟我提以往
别跟我提以往 2021-01-24 09:09

I\'m working on an assignment that is telling me to assume that I have a singly linked list with a header and tail nodes. It wants me to insert an item y before position p. Ca

7条回答
  •  没有蜡笔的小新
    2021-01-24 09:37

    create a node ptr
    ptr->info = item //item is the element to be inserted...
    ptr->next = NULL
    if (start == NULL) //insertion at the end...
        start = ptr
    else
        temp = ptr
        while (temp->next != NULL)
            temp = temp->next
        end while 
    end if
    if (start == NULL) //insertion at the beginning...
        start = ptr
    else
        temp = start
        ptr->info = item
        ptr->next = start
        start = ptr
    end if
    temp = start //insertion at specified location...
    for (i = 1; i < pos-1; i++)
        if (start == NULL)
            start = ptr
        else
            t = temp
            temp = temp->next
        end if
    end for
    t->next = ptr->next
    t->next = ptr
    

提交回复
热议问题