c_cpp 就地重新排列给定的链表。

Posted

tags:

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

//https://www.geeksforgeeks.org/rearrange-a-given-linked-list-in-place/
#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\n";
    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 split (node *head, node **aref, node **bref) {
    node *slow= head, *fast= head->next;
    while (fast && fast->next) {
        fast=fast->next;
        if (fast!=NULL) {
            slow=slow->next;
            fast=fast->next;
        }
    }
    *aref=head;
    *bref=slow->next;
    slow->next=NULL;
    return;
}

void reverse (node **bref) {
    node *b=*bref, *prev=NULL, *curr=*bref, *next;
    while(curr) {
        next=curr->next;
        curr->next=prev;
        prev=curr;
        curr=next;
    }
    *bref=prev;
}

void rearrange (node **headref) {
    node *a, *b;
    split(*headref, &a, &b);
    reverse(&b);
    node *head=NULL;
    while (a && b) {
        insert(&head, a->data);
        insert(&head, b->data);
        a=a->next;
        b=b->next;
    }
    if (a!=NULL)
        insert(&head, a->data);
    *headref=head;
}

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

以上是关于c_cpp 就地重新排列给定的链表。的主要内容,如果未能解决你的问题,请参考以下文章

数据结构第四章:带头节点的拆链表

c_cpp 给定单链表L:L0→L1→...→Ln-1→Ln,将其重新排序为:L0→Ln→L1→Ln-1→L2→Ln-2→......必须在不改变的情况下就地执行此操作节点

链表:链表分割

链表分割

链表分割

链表分割