链表的创建与逆序
#include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node *next; }Node; //创建链表 Node *CreateList(void) { int val,i,n; Node *head,*p,*q; head=NULL; printf("请输入您要建立的链表长度:\n"); scanf("%d",&n); printf("请输入您要输入的数据:\n"); for(i=0;i<n;i++) { scanf("%d",&val); p=(Node*)malloc(sizeof(Node)); p->data=val; if(head==NULL) { //q=p; head=p; } else { q->next=p; } q=p; } p->next=NULL; return head; } //链表的逆置 Node *ReverseList(Node *head) { if(head==NULL) { return NULL; } Node *pre,*cur,*ne; pre = head; cur = head->next; while(cur) { ne = cur->next; cur->next = pre; pre = cur; cur = ne; } head ->next = NULL; head = pre; return head; } //输出链表 void ShowList(Node *head) { Node *p; p=head; while(p) { printf("%d ",p->data); p=p->next; } printf("\n"); } void main() { Node *head; head=CreateList(); printf("链表逆置前的数据:\n"); ShowList(head); head=ReverseList(head); printf("链表逆置后的数据:\n"); ShowList(head); }