daAzai / C

0 stars 0 forks source link

链表倒序 #1

Open daAzai opened 5 years ago

daAzai commented 5 years ago

//2.通过指针将一个链表倒序

include

include

struct Data { char c; struct Data *next; };

int n;

struct Data creat1() { struct Data head; struct Data p1, p2; n = 0; p1 = p2 = (struct Data ) malloc (sizeof (struct Data)); scanf("%c", &p1->c); head = NULL; while (p1->c != '0') { n = n + 1; if (n == 1) {head = p1;} else {p2->next = p1;} p1->next = NULL; p2 = p1; p1 = (struct Data ) malloc (sizeof (struct Data)); scanf("%c", &p1->c); } p2->next = NULL; return (head); }

struct Data creat2(struct Data head) { struct Data p1, p2 = NULL; while (head) { p1 = head->next; head->next = p2; p2 = head; head = p1; } return p2; }

void print(struct Data head) { struct Data p; p = head; if (head != NULL) do { printf("%c", p->c); p = p->next; } while(p != NULL); }

int main() { struct Data *head; head = creat1(); print(head); printf("\n"); head = creat2(head); print(head); printf("\n"); return 0; }