Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Linked list operations. Write a code fragment for each (code fragment, not entir

ID: 3579001 • Letter: L

Question

Linked list operations. Write a code fragment for each (code fragment, not entire program!)(8pts)

*p, q, and r are pointers into the list

*Each node in the list has a val and next field

*Assume p, q, and r are initialized properly

A Print the larger of the 2 values of p and q

B Insert r between p & q in the list, where p & q are consecutive items

C Assume p and q point to items in a linked list and that p is to the left of q (p is before q). Write a loop that forces r to visit each node between p and q

p points to a node in the middle of the list(not beginning or end).

D Delete the node after p.

Explanation / Answer

(A)/* To find max value between two nodes of linked list */

int findLargest (ListNode *p) {
    int current = p->item;
    int next;

    if (p->next == NULL) {
        //The value at this node is obviously larger than a non-existent value
        return current;
    } else {
        //Recur to find the highest value from the rest of the LinkedList
        next = findLargest(p->next);
    }

    //Return the highest value between this node and the end of the list
    if (current > next) {
        return current;
    } else {
        return next;
    }
}

(B) /*For inserting a node r between two given nodes p and q */

void addafter(int num, int loc)
{
    int i;
    struct node *temp,*left,*right;
    right=head;
    for(i=1;i<loc;i++)
    {
    left=right;
    right=right->next;
    }
    temp=(struct node *)malloc(sizeof(struct node));
    temp->data=num;
    left->next=temp;
    left=temp;
    left->next=right;
    return;
}

(C)/* Well for visiting each node between p and q, we can visit nodes as:

struct Node *visitNode(struct Node *head, int n) {
Node *cur = head;
while(cur) {
  if(cur->data == n) return cur;
  cur = cur->next;
}

(D)/*For Deleting a node after a node*/

bool deleteNode(struct Node **head, Node *ptrDel) {
Node *cur = *head;
if(ptrDel == *head) {
  *head = cur->next;
  delete ptrDel;
  return true;
}
while(cur) {
  if(cur->next == ptrDel) {
   cur->next = ptrDel->next;
   delete ptrDel;
   return true;
  }
  cur = cur->next;
}
return false;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote