7-2 双向循环链表应用

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

#include<iostream>
#define ElemType int
using namespace std;

typedef struct DuLNode
{
    ElemType elem;
    struct DuLNode* prior;
    struct DuLNode* next;
}DuLNode,*DuLinkList;

DuLinkList input(DuLinkList& head, int x)
{
    head = new DuLNode;
    head->next = NULL;
    head->prior = NULL;
    head->elem = x;
    DuLNode* p, * q;
    p = head;
    for (int i = 0; i < x; i++)
    {
        q = new DuLNode;
        q->next = NULL;
        q->prior = p;
        p->next = q;
        cin >> q->elem;
        p = q;
    }
    return head;
}

DuLNode* getelem(DuLinkList L, int e)
{
    DuLNode* p;
    p = L->next;
    while (p && p->elem != e)
        p = p->next;
    return p;
}

void show(DuLinkList& head, int y)
{
    DuLNode* q;
    DuLNode* z = getelem(head, y);
    q = head->next;
    if (z == NULL)
    {
        cout << "未找到" << y;
        return;
    }
    while (q && q != NULL)
    {
        if (q != z->prior && q != z)
            cout << q->elem;
        else if (q == z->prior)
            cout << q->next->elem;
        else if (q == z)
            cout << q->prior->elem;
        q = q->next;
    }
}
int main()
{
    int a, b;
    DuLinkList head;
    cin >> a;
    head = input(head, a);
    cin >> b;
    show(head, b);
    return 0;
}

 

posted @ 2022-10-24 23:52  旺旺大菠萝  阅读(43)  评论(0编辑  收藏  举报