answersLogoWhite

0


Best Answer

#include<iostream>

#include<list>

int main()

{

// the linked list (of integers)

std::list<int> List;

// insertions:

List.push_back (42);

List.push_back (99);

List.push_back (60);

List.push_front (55);

// point to first node

std::list<int>::iterator n = List.begin();

// advance to next node

++n;

// insert in front of node n

list.insert (n, 33);

// print list:

for (auto node : List) std::cout << node << std::endl;

}

User Avatar

Wiki User

9y ago
This answer is:
User Avatar
More answers
User Avatar

AnswerBot

6mo ago

Here's a C++ code snippet to implement a linked list:

#include <iostream>

struct Node {
    int data;
    Node* next;
};

Node* createNode(int value) {
    Node* newNode = new Node;
    newNode->data = value;
    newNode->next = nullptr;
    return newNode;
}

void insertNode(Node** head, int value) {
    Node* newNode = createNode(value);
    
    if (*head == nullptr) {
        *head = newNode;
    } else {
        Node* temp = *head;
        while (temp->next != nullptr) {
            temp = temp->next;
        }
        temp->next = newNode;
    }
}

void displayList(Node* head) {
    Node* temp = head;
    while (temp != nullptr) {
        std::cout << temp->data << " ";
        temp = temp->next;
    }
    std::cout << std::endl;
}

int main() {
    Node* head = nullptr;
    
    insertNode(&head, 5);
    insertNode(&head, 10);
    insertNode(&head, 15);
    
    displayList(head);
    
    return 0;
}

This code creates a struct Node with a data variable and a next pointer. The createNode function creates a new node and returns a pointer to it. The insertNode function inserts a new node at the end of the linked list. The displayList function prints the values of all nodes in the linked list. Finally, in the main function, we create a linked list and display its elements.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: WAP in c plus plus to implement linked list?
Write your answer...
Submit
Still have questions?
magnify glass
imp