Closed xyweiying closed 5 years ago
struct node { int data; struct node *next; };
//链表正序 struct node front() { struct node head,p,q; int i = 0; head = p = q = (struct node )malloc(sizeof(struct node)); scanf("%d",&p->data); head = p; while(p->next->data != 0) { i++; if(i == 1) { q = (struct node )malloc(sizeof(struct node )); scanf("%d",&q->data); head->next = q; } else { p = q; q = (struct node )malloc(sizeof(struct node )); scanf("%d",&q->data); p->next = q; } } p->next = null; return head; } //链表倒序 struct node reverse(struct node head) { int i = 0; struct node p,q; q = head; p = head->next; q->next = null; while(p->next != 0) { i++; if(i == 1) { head = head; } if(i == 2) { head = p; } else { head = p->next; p->next = q; q = p; p = head; } } p->next = q; return p; } //输出 void print(struct node head) { struct node *q; q = head; while(q != null) { printf("%5d",q->data); q = q->next; } }
main() { struct node *head; printf("输入数据:"); head = front(); printf("正序输出:\n"); print(head);
printf("\n"); printf("倒序输出:\n"); head = reverse(head); print(head); }
点评:
修改!
include"stdio.h"
define null 0
include"stdlib.h"
struct node { int data; struct node *next; };
//链表正序 struct node front() { struct node head,p,q; int i = 0; head = p = q = (struct node )malloc(sizeof(struct node)); scanf("%d",&p->data); head = p; while(p->next->data != 0) { i++; if(i == 1) { q = (struct node )malloc(sizeof(struct node )); scanf("%d",&q->data); head->next = q; } else { p = q; q = (struct node )malloc(sizeof(struct node )); scanf("%d",&q->data); p->next = q; } } p->next = null; return head; } //链表倒序 struct node reverse(struct node head) { int i = 0; struct node p,q; q = head; p = head->next; q->next = null; while(p->next != 0) { i++; if(i == 1) { head = head; } if(i == 2) { head = p; } else { head = p->next; p->next = q; q = p; p = head; } } p->next = q; return p; } //输出 void print(struct node head) { struct node *q; q = head; while(q != null) { printf("%5d",q->data); q = q->next; } }
main() { struct node *head; printf("输入数据:"); head = front(); printf("正序输出:\n"); print(head);
printf("\n"); printf("倒序输出:\n"); head = reverse(head); print(head); }