c_cpp 旋转链接列表

Posted

tags:

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

// https://www.geeksforgeeks.org/rotate-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;
}

void insert(node **headref, int n) {
    node* last = *headref;
    node *temp=new node;

    temp->data = n;
    temp->next=NULL;
    if (last == NULL) {
        *headref = temp;
        return;
    }
    while (last->next)
        last = last->next;
    last->next = temp;
    return;
}

void rotate(node **headref, int k) {
    node *tempk = *headref;
    while (k>1){
        tempk = tempk->next;
        k--;
    }
    if (tempk == NULL)
        return;

    node *last = tempk;
    while (last->next)
        last = last->next;
    last->next = *headref;
    *headref = tempk->next;
    tempk->next = NULL;
}

int main() {
    int n;
    node *head=NULL;
    while (true) {
        cout<< "Enter the number: ";
        cin>>n;
        if (n==-9)
            break;
        else
            insert(&head,n);
    }
    cout<< "Enter k: ";
    cin>>n;
    cout<< "Before rotating: ";
    print(head);
    rotate(&head, n);
    cout<< "\nAfter rotating: ";
    print(head);
}

以上是关于c_cpp 旋转链接列表的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 链接列表

c_cpp 链接列表。

c_cpp 203.删除链接列表元素

c_cpp 链接列表实现与类

c_cpp 链接列表的合并排序

c_cpp 使用类链接列表实现