Answer to Question #241227 in Algorithms for Selma

Question #241227
Identify the steps you would take to carry out each of the following operations on a linked-list data
structure and then implement an algorithm in pseudocode to solve problem as guided by the steps you
have identified.
1. Insert a new node at the beginning of a linked list
2. Delete the first node in a linked list
3. Write a program that counts the number of nodes in a linked list
4. Insert a new node at the end of a linked list.
5. Write a program that prints the contents of the linked list.
1
Expert's answer
2021-09-23T17:46:25-0400

1.

struct node
{
    int data;
    struct node *next;
};
struct node *head = NULL;
void addFirst(struct node **head, int val)
{
          struct node *newNode = malloc(sizeof(struct node));
          newNode->data = val;
    }
void addFirst(struct node **head, int val)
{
      struct node *newNode = malloc(sizeof(struct node));
      newNode->data = val;
      newNode->next = *head;
}

2.
Algorithm to delete first node of Singly Linked List
Input:  head of the linked list
Begin:
    If (head != NULL) then
        Delete ← head
        head ← head.next
        unalloc (toDelete)
    End if
End

3. 

struct node* temp = head;
int count=0;
    while(temp != NULL){
       temp = temp->next;
        count++;
    }
    printf("\n Total no. of nodes is %d",count);
}

4.
struct node
{
    int data;
    struct node *next;
};
struct node *head = NULL;
void addLast(struct node **head, int val)
{
    struct node *newNode = malloc(sizeof(struct node));
    newNode->data = val;
    newNode->next = NULL;
}
void addLast(struct node **head, int val)
{
    struct node *newNode = malloc(sizeof(struct node));
    newNode->data = val;
    newNode->next     = NULL;
    if(*head == NULL)
         *head = newNode;
}

5.
typedef struct node{
    int value;
    struct node *next; 
}node;

void printList(node *head){
    node *tmp = head;
    while(tmp != NULL){
        if(tmp->next == NULL){
            printf("%d", tmp->value);
        }else{
            printf("%d, ", tmp->value);
        }
        tmp = tmp->next;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS