n个节点的二叉树n+1_使用C ++程序删除链接列表的M个节点后的N个节点

n个节点的二叉树n+1

Problem statement:

问题陈述:

Given a Linked List, we have to delete N numbers of nodes after the M numbers of nodes.

给定一个链表,我们必须在M个节点之后删除N个节点。

Example:

例:

    Input: 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10
    N=2, M=3
    Output: 1 → 2 → 3 → 6 → 7 → 8

    Input: 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → 9 → 10 → 11
    N=3, M=3
    Output: 1 → 2 → 3 → 7 → 8 → 9

Algorithm:

算法:

To solve that problem we simply use the Brute-Force method. We traverse the linked list from the head node and delete N nodes after traversing M nodes. If there are less than N nodes to delete then we simply delete that nodes and stop traversing.

为了解决该问题,我们仅使用Brute-Force方法 。 我们从头节点遍历链表,并在遍历M个节点后删除N个节点 。 如果要删除的节点少于N个,则我们只需删除该节点并停止遍历即可。

C++ implementation:

C ++实现:

#include <bits/stdc++.h>
using namespace std;

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

//Create a new node
struct node* create_node(int x)
{
    struct node* temp = new node;
    temp->data = x;
    temp->next = NULL;
    return temp;
}

//Enter the node into the linked list
void push(node** head, int x)
{
    struct node* store = create_node(x);
    if (*head == NULL) {
        *head = store;
        return;
    }
    struct node* temp = *head;
    while (temp->next) {
        temp = temp->next;
    }
    temp->next = store;
}

//Reverse the linked list
void delete_node(node* head, int m, int n)
{
    struct node* temp = head;
    int count = 1;
    while (1) {
        while (temp && count < m) {
            temp = temp->next;
            count++;
        }
        if (temp == NULL || temp->next == NULL) {
            return;
        }
        count = 1;
        struct node* store = temp;
        temp = temp->next;
        while (temp && count < n) {
            temp = temp->next;
            count++;
        }
        if (temp == NULL) {
            return;
        }
        store->next = temp->next;
        temp = temp->next;
    }
}

//Print the list
void print(node* head)
{
    struct node* temp = head;
    while (temp) {
        cout << temp->data << " ";
        temp = temp->next;
    }
}

int main()
{
    struct node* l = NULL;
    push(&l, 1);
    push(&l, 2);
    push(&l, 3);
    push(&l, 4);
    push(&l, 5);
    push(&l, 6);
    cout << "Before the delete operation" << endl;
    print(l);
    delete_node(l, 3, 2);
    cout << "\nAfter the delete operation" << endl;
    print(l);

    return 0;
}

Output

输出量

Before the delete operation
1 2 3 4 5 6
After the delete operation
1 2 3 6


翻译自: https://www.includehelp.com/cpp-programs/delete-n-nodes-after-m-nodes-of-a-linked-list-using-cpp-program.aspx

n个节点的二叉树n+1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值