#include<assert.h>
typedef struct SLnode
{
int data;
struct SLnode* prior;
struct SLnode* next;
}SLnode,*SLnodelist;
//创建结点
SLnode* createhead(int data)
{
SLnode* newnode = (SLnode*)malloc(sizeof(SLnode));
newnode->data = data;
newnode->next = newnode->prior = newnode;
return newnode;
}
//初始化哨兵位
SLnode* ListInit()
{
SLnode* newnode = createhead(0);
}
//尾插
void ListPushBank(SLnode* plist, int x)
{
assert(plist);
SLnode* ret = plist->prior;
SLnode* newnode = createhead(x);
ret->next = newnode;
newnode->next = plist;
newnode->prior = ret;
plist->prior = newnode;
}
void printlist(SLnode* plist)
{
SLnode* ret = plist->next;
while (ret != plist)
{
printf("%d->", ret->data);
ret = ret->next;
}
printf("NULL\n");
}
void change(SLnodelist p)
{
SLnodelist q;
q = p->prior;
q->prior->next = p;
p->prior = q->prior;
q->next = p->next;
p->next->prior = q;
q->prior = p;
p->next = q;
}
int main()
{
int n, num;
SLnode* plist = ListInit();
printf("请输入链表的长度\n");
scanf("%d", &n);
printf("请输入元素\n");
for (int i = 0; i < n; i++)
{
scanf("%d", &num);
ListPushBank(plist,num);
}
printf("双链表的元素如下\n");
printlist(plist);
printf("请输入你要交换的的结点的值\n");
SLnodelist q = (SLnodelist)malloc(sizeof(SLnode));
scanf("%d", &q->data);
SLnodelist p;
p = plist->next;
while (p != plist)
{
if (p->data == q->data)
{
change(p);
break;
}
else
{
p = p->next;
}
}
printf("交换后\n");
printlist(plist);
return 0;
}
已知p指向双向循环链表中的一个结点,其结点结构为data、prior、next三个域,写出算法change(p),交换p所指向的结点和它的前缀结点的顺序。
最新推荐文章于 2024-08-15 22:41:27 发布