单链表就地逆转问题!!!有那位高手来帮下忙!!
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
void CreateList(LinkList &L,int n)
{
L=(LinkList)malloc(sizeof(LNode));
L->data=0;
L->next=NULL;
for(int i=n;i>0;--i)
{
LinkList p=(LinkList)malloc(sizeof(LNode));
printf("Input:\n");
scanf("%d",&p->data);
p->next=L->next;
L->next=p;
}
}
void main()
{
LinkList La,Lb,Lc;
CreateList(La,5);
Lb=La;
Lc=La->next;
while(Lc->next)
{
Lc->next->next=Lc;
Lc=Lc->next;
}
Lb->next->next=NULL;
Lb->next=Lc;
while(Lb->next)
{
printf("%d\n",Lb->data);
Lb=Lb->next;
}
}
[解决办法]
#include <stdio.h>#include <stdlib.h> typedef struct LNode{ int data; struct LNode *next; }LNode,*LinkList; void CreateList(LinkList *L, int n) { int i; LinkList p; /* *L = (LinkList)malloc(sizeof(LNode)); (*L)->data = 0; (*L)->next = NULL; */ *L = NULL; for(i = n;i > 0;--i) { p = (LinkList)malloc(sizeof(LNode)); printf("Input:\n"); scanf("%d", &p->data); p->next = (*L); (*L) = p; } } int main(void) { LinkList La, Lb, Lc; CreateList(&La, 5); Lb = La; Lc = NULL; while(Lb != NULL) { La = Lb->next; Lb->next = Lc; Lc = Lb; Lb = La; } //Lb->next->next = NULL; Lb = Lc; while(Lb != NULL) { printf("%d\n", Lb->data); Lb = Lb->next; } return 0; }
[解决办法]
LinkList * reverse(LinkList * L){ LinkList * L0; if(L->next==NULL) return L; L0 = reverse(L->next); L0->next=L; L->next=NULL; return L0;}