linked list k Find and clear the element (c++)

Asked 2 years ago, Updated 2 years ago, 24 views

It's a program that connects elements (e1, e2, ..., en) of the list given to the Singly Linked List in chain format and stores elements (e1, ..., en). (The link of the last node in the Singlely Linked List must be null.)

The problem is the same as above, so I made it as below.

#include <iostream>
#include <stdlib.h>
    using namespace std;

    class LinkedList {
        struct Node {
            int x;
            Node *next;
        };
    public:
        LinkedList() {
            head = NULL; 
        }
        void addValue(int val) {
            Node *n = new Node();   
            n->x = val;            
            n->next = head;        

            head = n;               
        }
    private:
        Node *head;
    };

    int main() {
        LinkedList list;
        How many LISTs do you want to enter the cout <<"";
        int n;
        cin >> n;
        if (n <= 0) return 0;
        int *p = new int[n];
        for (int i = 0; i < n; i++) {
            list.addValue(p[i]);
        }
    }

From the above program

Programs that delete kth node

A program that adds a new node between the kth node and the k+1th node

to squeeze something

1. I don't know how to get the pointer value of the node I want to delete.

2. If I write delete when deleting, will the data value of that node be completely erased?

Please give me an example of the program. I will refer to it when I study.

c++

2022-09-22 08:09

1 Answers

The pointer value of the kth node can be moved k-1 times along the next at the first node.

Node *delete_target = head;
for(int i=0;i<k-1;i++){
    delete_target = delete_target -> next;
}

I can do it like this.


2022-09-22 08:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.