赞
踩
双链循环链表排序:
原链表: 1 2 3 4 5 6 7 8 9 10
逆序后:10 9 8 7 6 5 4 3 2 1
思路:
把最后一个节点删除, 插到head下面去
数据 1 不用管, 把后面的数据往 1 前面怼, 1自然就是最后一个了
提示:需要一个指针记录一下最后一个值 p 的位置;(看自身代码情况);
思路图如下:
- #include <stdio.h>
- #include <stdlib.h>
- #define SIZE 10
- typedef struct lint
- {
- int data;
- struct lint *prev;
- struct lint *next;
- } lint, *plist;
-
-
- void stamp(plist head);
-
-
- //创建头节点
- plist LOCK(void)
- {
- plist head = malloc(sizeof(lint));
- if (head == NULL)
- {
- printf("head errer\n");
- return NULL;
- }
- head->data = 0;
- head->prev = head;
- head->next = head;
- return head;
- }
-
- // 创建新节点
- plist Her_a(int data)
- {
- plist new = malloc(sizeof(lint));
- if (new == NULL)
- {
- printf("new erreo\n");
- return NULL;
- }
- new->data = data;
- new->prev = NULL;
- new->next = NULL;
- }
-
- // 尾部插入
- int Wak_a(plist head, int data)
- {
- plist newnode = Her_a(data);
-
- plist p = head;
- while (p->next != head)
- {
- p = p->next;
- }
-
- p->next = newnode;
- newnode->prev = p;
- newnode->next = head;
- head->prev = newnode;
- return 0;
- }
-
- //循环插入
- void cha(plist head)
- {
- for (int i = 1; i <= SIZE; i++)
- {
- Wak_a(head, i);
- }
- }
-
- // 打印
- void stamp(plist head)
- {
- plist p = head->next;
- printf("-head");
- while (p != head)
- {
- printf("-%d", p->data);
- p = p->next;
- }
- printf("\n");
- }
-
- //删除最后一个节点
- void mak_a(plist p)
- {
- p->prev->next = p->next;
- p->next->prev = p->prev;
- p->next = p->prev = NULL;
- }
-
- // 头插
- void mak_b(plist p, plist head)
- {
- p->next = head->next;
- head->next = p;
- p->next->prev = p;
- p->prev = head;
- }
-
-
- // 交换数据
- int Her_b(plist head)
- {
- if(head->next == head)
- {
- printf("此节点没有数据\n");
- return -1;
- }
-
- plist p = head->next;
- plist q = NULL;
-
- while(p != head)
- {
- // q 负责记录 P 原先的位置 1 位置不用变, 直接往前怼就完事了
- q = p->next;
- mak_a(p);//删除结点
- mak_b(p, head);//交换节点
- p = q;
- }
- }
-
-
- int main(int argc, char const *argv[])
- {
- plist myhead = LOCK();
- cha(myhead);//循环尾部插入数据
- stamp(myhead);//打印
- Her_b(myhead);//交换数据
- stamp(myhead);//打印
- return 0;
- }
执行完毕图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。