数据结构实验2

7-2 双向循环链表应用
已知p指向双向循环链表中的一个结点,其结点结构为data、prior、next三个域,实现交换p所指向的结点和它的前缀结点的顺序。

输入格式:
第一行输入元素个数,第二行输入元素值,第三行输入要交换的元素值,第四行输出结果。

输出格式:
输出交换后的结果,中间不用空格分隔,若要交换的值:4,不在数组终,则输出“未找到4”

输入样例:
在这里给出一组输入。例如:

6
1 2 3 4 5 6
6
输出样例:
在这里给出相应的输出。例如:

123465、

代码:

#include<stdio.h>
#include<stdlib.h>

typedef struct Node{
    int data;
    struct Node *prior,*next;
}Node;

Node* createList(int n,int values[]){
    Node *head=NULL,*tail=NULL,*newNode;
    for(int i=0;i<n;i++){
        newNode=(Node*)malloc(sizeof(Node));
        newNode->data=values[i];
        newNode->prior=tail;
        newNode->next=head;
        if(tail){
            tail->next=newNode;
        }else{
            head=newNode;
        }
        if(head){
            head->prior=newNode;
        }
        tail=newNode;
    }
    return head;
}

Node*findNode(Node *head,int value){
    Node *current=head;
    if(current){
        do{
            if(current->data==value){
                return current;
            }
            current=current->next;
        }while(current!=head);
    }
    return NULL;
}

void swapNodes(Node *p){
    if(p==NULL||p->prior==NULL)return ;

    Node *prev=p->prior;
    Node *next=p->next;

    if(prev->prior){
        prev->prior->next=p;
    }
    if(next){
        next->prior=prev;
    }
    prev->next=next;
    p->prior=prev->prior;
    p->next=prev;
    prev->prior=p;

    if(p->prior==NULL){
        p->prior=prev;
    }
}

void printList(Node *head){
    Node* current=head;
    if(current){
        do{
            printf("%d",current->data);
            current=current->next;
        }while(current!=head);
    }
    printf("\n");
}

int main(){
    int n,value,swapValue;
    scanf("%d",&n);

    int values[n];
    for(int i=0;i<n;i++){
        scanf("%d",&values[i]);
    }

    scanf("%d",&swapValue);

    Node *head=createList(n,values);
    Node *p=findNode(head,swapValue);
    
    if(p){
        swapNodes(p);
        printList(head);
    }else{
        printf("未找到%d\n",swapValue);
    }
    
    return 0;
}
posted @ 2025-01-10 16:48  呓语-MSHK  阅读(16)  评论(0)    收藏  举报