c_cpp 删除链接列表的备用节点

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 删除链接列表的备用节点相关的知识,希望对你有一定的参考价值。

// https://www.geeksforgeeks.org/delete-alternate-nodes-of-a-linked-list/
#include <iostream>
#include <list>
using namespace std;

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

void print (node* n) {
    while (n) {
        cout<< n->data<< "->";
        n=n->next;
    }
    cout<< "NULL";
    return;
}

node* insert (node* head, int n) {
    node* temp = (node*)malloc(sizeof(node));
    temp->data = n;
    temp->next = NULL;

    if (head == NULL) {
        head = temp;
        return head;
    }
    node* last = head;
    while (last->next)
        last = last->next;
    last->next = temp;
    return head;
}

node* DeleteAlternate (node* head) {
    if (head && head->next) {
        node* temp = head->next;
        head->next = temp->next;
        free(temp);
        DeleteAlternate(head->next);
    }
    return head;

}

int main () {
    int n;
    node* head = NULL;

    while (true) {
        cout<< "Enter the number: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head= insert(head,n);
    }
    print(head);
    head = DeleteAlternate(head);
    cout<< "\n";
    print(head);
}
// https://www.geeksforgeeks.org/delete-alternate-nodes-of-a-linked-list/
#include <iostream>
#include <list>
using namespace std;

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

void print (node* n) {
    while (n) {
        cout<< n->data<< "->";
        n=n->next;
    }
    cout<< "NULL";
    return;
}

node* insert (node* head, int n) {
    node* temp = (node*)malloc(sizeof(node));
    temp->data = n;
    temp->next = NULL;

    if (head == NULL) {
        head = temp;
        return head;
    }
    node* last = head;
    while (last->next)
        last = last->next;
    last->next = temp;
    return head;
}

node* DeleteAlternate (node* head) {
    node* temp = head, *next = NULL;
    while (temp && temp->next) {
        next = temp->next->next;
        free(temp->next);
        temp->next = next;
        temp = temp->next;
    }
    return head;
}

int main () {
    int n;
    node* head = NULL;

    while (true) {
        cout<< "Enter the number: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head= insert(head,n);
    }
    print(head);
    head = DeleteAlternate(head);
    cout<< "\n";
    print(head);
}

以上是关于c_cpp 删除链接列表的备用节点的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 链接列表|设置3(删除节点)

c_cpp 237.删除链接列表中的节点

c_cpp 使用第二级指针删除链接列表节点

c_cpp 237.删除链接列表中的节点 - 简单-2018.82

c_cpp 给定已排序的链接列表,删除所有具有重复数字的节点,只留下原始列表中的不同数字。

c_cpp 在链接列表中隔离偶数节点和奇数节点