单链表的反转问题

来源:互联网 发布:工业打标机软件 编辑:程序博客网 时间:2024/06/06 02:30

总是有些笔试会碰到

#include<stdio.h>#include<stdlib.h>#define n 5typedef struct node{int num;struct node* next;}*nodelist,node;int a[n];nodelist create(int m,int *a){nodelist L;nodelist head;int i=0;head = (node *)malloc(sizeof(int));head->num=0;L=head;for(i=0; i<n; i++){L->next = (node *)malloc(sizeof(int));L = L->next;L->num = a[i];}L->next = NULL;return head;}void show(nodelist head){nodelist L=head;while(L != NULL){printf("%d",L->num);L=L->next;}printf("\n");}//单链表反转nodelist reverse(nodelist head){nodelist L=head;nodelist pre=NULL;nodelist pafter=NULL;do{pafter = L->next;L->next = pre;pre = L;L = pafter;}while(L != NULL);return pre;}int main(){nodelist list;list = (node *)malloc(sizeof(int));int i,a[n];for(i=0;i<n;i++){scanf("%d",&a[i]);}list = create(n,a);show(list);list = reverse(list);show(list);return 0;}


0 0
原创粉丝点击