单链表逆序怎么出不来
# include <stdio.h>
# include <malloc.h>
# define null 0
typedef struct node {
int data;
struct node *next;}lnode,*linklist;
linklist creat(linklist head, int n)
{linklist p;
int i;
scanf("%d",&n);
head=(linklist)malloc(sizeof(lnode));
head->next=null ;
for(i=n;i>0;i--)
{p =(linklist)malloc(sizeof(lnode));
scanf("%d",&p->data);
p->next=head->next ;
head->next=p ;}
return head;
}
void print(lnode* p)
{printf("输出单链表为:");
while(p->next!=null)
{
printf("\n%d\n",p->next->data);
p=p->next;}
}
linklist invert(linklist head)
{
linklist s,p;
s=(lnode*)malloc(sizeof(linklist));
s->next=null;
p=head;
while(p)
{p->next=s;s=p;
p=p->next;
return s;}
}
void print2(lnode* s)
{printf("输出单链表逆序为:");
while(s->next!=null)
{
printf("\n%d\n",s->next->data);
s=s->next;}
}
void main()
{ linklist head,s;
head=null;s=null;int n;
printf("请输入元素个数及元素值\n");
head=creat(head,n);
print(head);
head=invert(head);
print2(s);
}
[解决办法]
linklist invert(linklist head)
{
linklist s,p;
s=(lnode*)malloc(sizeof(linklist));
s->next=null;
p=head;
while(p)
{p->next=s;s=p;
p=p->next;
return s;}
}
==>
linklist invert(linklist head)
{
linklist s,p,q;
s=head;
p=head;
while(p)
{
q=p->next;
p->next=s;s=p;
p=q;
}
return s;
}
[解决办法]
刚巧昨天写了一个,仅供参考
#include <stdio.h>#include <stdlib.h>typedef struct Node{ int data; struct Node *next;} Node;Node *CreateList();Node *Inverse(Node *head);void Display(Node *head);void DestoryList(Node **head);int main(){ Node *head = CreateList(); Display(head); head = Inverse(head); Display(head); DestoryList(&head); return 0;}Node *CreateList(){ int i; Node *p, *q; Node *head = (Node *)malloc(sizeof(Node)); head->next = NULL; p = head; while (scanf("%d", &i) == 1) { q = (Node *)malloc(sizeof(Node)); q->data = i; q->next = NULL; p->next = q; p = q; } return head;}Node *Inverse(Node *head){ Node *p = head->next, *q; if (p != NULL) { q = p; p = p->next; q->next = NULL; } while (p != NULL) { q = p; p = p->next; q->next = head->next; head->next = q; } return head;}void Display(Node *head){ Node *p = head->next; while (p != NULL) { printf("%5d", p->data); p = p->next; } printf("\n");}void DestoryList(Node **head){ Node *p = (*head)->next, *q; while (p != NULL) { q = p; p = p->next; free(q); } free(*head);}