c_cpp 以给定大小的组反转链接列表设置2

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 以给定大小的组反转链接列表设置2相关的知识,希望对你有一定的参考价值。

// https://www.geeksforgeeks.org/reverse-linked-list-groups-given-size-set-2/
#include <bits/stdc++.h>
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 = new 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* ReverseList (node* head, int k) {
    node *current = head, *prev = NULL;
    stack <node*> s;

    while (current) {
        int c = 0;
        while (current && c<k) {
            s.push(current);
            current = current->next;
            c++;
        }
        while (s.size() > 0) {
            if (prev == NULL) {
                prev = s.top();
                head = prev;
                s.pop();
            }
            else {
                prev->next = s.top();
                prev = prev->next;
                s.pop();
            }
        }
    }
    prev->next = NULL;
    return head;
}

int main() {
    int n,k;
    node* head=NULL;
    while (true) {
        cout<< "Enter the number: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head = insert(head, n);
    }
    print(head);
    cout<< "Enter the set size: ";
    cin>> k;
    head = ReverseList(head,k);
    print(head);
}

以上是关于c_cpp 以给定大小的组反转链接列表设置2的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp GFG以给定大小的组反转数组

c_cpp 打印链接列表的反向而不实际反转

c_cpp 删除给定位置的链接列表节点

c_cpp 给定一个链接的线段列表,删除中间点

c_cpp 将最后一个元素移动到给定链接列表的前面

c_cpp 链接列表|设置2(插入节点)