Algorithm InsertList (List, pos, val) allocate (insertNode) set insertNode value
ID: 3583898 • Letter: A
Question
Algorithm InsertList (List, pos, val)
allocate (insertNode)
set insertNode value to val
set insertNode next pointer to NULL
//inserting to an empty list
if(list is empty)
set list tail and head to this new.
//inserting to the beginning of the list
else if (pos equals to 1)
set insertNode next to list head next
set list head to insert node
//Inserting at the end of the list
if (pos greater or equal to list size + 1)
set list tail next pointer to insertNode
set list tail pointer to insert
//Inserting in the middle of the list
else
locate node at position pos-1 and set this to temp
set insertNode next pointer to temp next pointer
set temp next pointer to insert
increment the size of the list by 1
-------------------------------------------------
Algorithm DeleteList (List, val)
if (list is not empty)
define a temp node
set temp node to list head
loop (temp next is not null and temp next val is not equal to val)
set temp to temp next pointer
end loop
if (temp next equal to NULL)
print element not found in the linked list message
else
define a remove node
set remove node equal to temp next
set temp next to point to temp next next node
free remove node
decrement list size by one
if (list size equal to 0)
set list tail equal to list head
else
print list is empty message
need these two function.When i do that i always get a cmd error.(it shuts the cmd when i try to add value )
Explanation / Answer
void insertList(struct ListRecord *l,int pos,int val)
{
if(pos > (l->size+1))
pos=l->size+1;
if(pos == l->size+1)
{
struct Node *tmp;
l->tail->next=tmp;
tmp->val=val;
tmp->next=NULL;
l->tail=tmp;
l->size++;
}
else
{
struct Node *tmp;
tmp=l->head;
for(int i=0;i<pos;i++)
{
tmp=tmp->next;
}
struct Node *insert;
insert->val=val;
insert->next=tmp->next;
tmp->next=insert;
l->size++;
}
}
int deleteList(struct ListRecord *l,int val)
{
if (!head || !(*head))
return -1;
ListRecord *tmp = *head;
ListRecord *prev = NULL;
while (tmp->value != val && tmp->next != NULL)
{
prev = tmp;
temp = temp->next;
}
if (tmp->value == val)
{
if (prev)
{
prev->next = tmp->next;
}
else
{
*head = tmp->next;
}
free(tmp);
return val;
}
return -1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.