错误蛋疼的反转 temp引用的地址已经被改变了所以不能实现反转
105 void reverse(void)
106 {
107 link node = head->next;
108 link temp;
109 temp = head;
110 head->next = head->pre;
111 head->pre = temp ->next;
112 while(node!=head){
113 temp = node;
114 node->next = node->pre;
115 node->pre = temp->next;
116 node = temp->next;
117 }
118 }
119
120
- 蛋疼的反转
- 105 void reverse(void)
- 106 {
- 107 link node = head->next;
- 108 link temp;
- 109 temp = head;
- 110 head->next = head->pre;
- 111 head->pre = temp ->next;
- 112 while(node!=head){
- 113 temp = node->next;
- 114 node->next = node->pre;
- 115 node->pre = temp;
- 116 node = temp;
- 117 }
- 118 }
- 119
- 120
- 100 //通过pre照样能实现反序
- 101 for(; node->pre!=head; node=node->pre){
- 102 printf("node->item=%d\n", node->pre->item);
- 103 }
- 104
- 1 /* circular.h */
- 2
- 3 #ifndef CIRCULAR_H
- 4 #define CIRCULAR_H
- 5
- 6 typedef struct node *link;
- 7 struct node {
- 8 int item;
- 9 link pre, next;
- 10 };
- 11
- 12 link make_node( int item);
- 13 void free_node(link p);
- 14 link search( int key);
- 15 void insert(link p);
- 16 void delete(link p);
- 17 void traverse(void (*visit)(link));
- 18 void destroy(void);
- 19 void enqueue(link p);
- 20 link dequeue(void);
- 21 link get_head(void);
- 22 void list_node(void);
- 23 void reverse(void);
- 24 #endif
- 1 /* circular.c */
- 2 #include <stdlib.h>
- 3 #include <stdio.h>
- 4 #include "circular.h"
- 5
- 6 struct node sentinel = {0, &sentinel, &sentinel};
- 7
- 8 static link head = &sentinel;
- 9
- 10 link make_node( int item)
- 11 {
- 12 link p = malloc(sizeof *p);
- 13 p->item = item;
- 14 p->pre = p->next = NULL;
- 15 return p;
- 16 }
- 17
- 18 void insert(link p)
- 19 {
- 20 p->next = head->next;
- 21 head->next->pre = p;
- 22 head->next = p;
- 23 p->pre = head;
- 24 }
- 25
- 26 void delete(link p)
- 27 {
- 28 p->pre->next = p->next;
- 29 p->next->pre = p->pre;
- 30 }
- 31
- 32
- 33
- 34 void free_node(link p)
- 35 {
- 36 free(p);
- 37 }
- 38
- 39 link search( int key)
- 40 {
- 41 link p;
- 42 for(p=head->next; p!=head; p=p->next){
- 43 if(p->item == key){
- 44 return p;
- 45 }
- 46 }
- 47 return NULL;
- 48 }
- 49
- 50 void traverse(void (*visit)(link))
- 51 {
- 52 link p;
- 53 for(p=head->next; p!=head; p=p->next){
- 54 visit(p);
- 55 }
- 56 }
- 57
- 58
- 59 void destroy(void)
- 60 {
- 61 link q, p = head->next;
- 62 head->next = head;
- 63 head->pre = head;
- 64 while(p!=head){
- 65 q = p;
- 66 p=p->next;
- 67 free_node(q);
- 68 }
- 69 }
- 70
- 71 void enqueue(link p)
- 72 {
- 73 insert(p);
- 74 }
- 75
- 76 link dequeue(void)
- 77 {
- 78 if(head->pre ==head){
- 79 return NULL;
- 80 }else{
- 81 link p = head->pre;
- 82 delete(p);
- 83 return p;
- 84 }
- 85 }
- 86
- 87
- 88 link get_head(void)
- 89 {
- 90 return head;
- 91 }
- 92
- 93 void list_node(void)
- 94 {
- 95 link node = head;
- 96 for(; node->next!=head; node=node->next){
- 97 printf("node->item=%d\n", node->next->item);
- 98 }
- 99 }