1 回答

TA貢獻(xiàn)1757條經(jīng)驗 獲得超7個贊
你的creat函數(shù)中有個錯誤還是很明顯的,我看出來了,就給你改過來了。
#include <stdlib.h>
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
typedef struct LNode
{
int data;
struct LNode *next;
} LNode, *LinkList;
void Creat_List_L(LinkList &L,int n)
{
int i;
int *array=(int *)malloc(n*sizeof(int));//array數(shù)組用內(nèi)存動態(tài)分配比較好,用new的話是:int *array=new int[n],對應(yīng)delete []array
LNode *q,*head=NULL;
head=L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
for(i=0;i<n;i++)
{
cout<<"請輸入數(shù)據(jù):"<<endl;
scanf("%d",&array[i]);
}
for(i=n-1;i>=0;i--)
{
q=(LinkList)malloc(sizeof(LNode));
q->data=array[i];
q->next=L->next;
L->next=q;//你原來這樣寫,最后L不是指向鏈表的頭結(jié)點了,所以下面執(zhí)行逆置函數(shù)就會出錯,所以我上面定義了一個head,用來存放頭結(jié)點的地址,這樣輸出鏈表初始狀態(tài)時就可以用了
}
cout<<"逆置前L:"<<endl;
while(head->next)
{
head=head->next;
cout<<head->data;
if(head->next!=NULL)
cout<<" -> ";
}
cout<<endl;
free(array);
}
//創(chuàng)建鏈表;
void Contray_List(LinkList &L)//參數(shù)&n沒用
{
LinkList p,q,s;
//沒用的我都注釋掉了
//int i;
//p=(LinkList)malloc(sizeof(LNode));
//q=(LinkList)malloc(sizeof(LNode));
//s=(LinkList)malloc(sizeof(LNode));
p=L;
p=p->next;
q=p->next;
p->next=NULL;
while(q!=NULL)
{
s=q->next;
q->next=p;
p=q;
q=s;
}
L=p;
cout<<"逆置完成!"<<endl;
} //逆置函數(shù)
void main()
{
LinkList L;
LNode *m,*p;
int n;
cout<<"請輸入數(shù)據(jù)的個數(shù):"<<endl;
scanf("%d",&n);
Creat_List_L(L,n);
cout<<"開始逆置..."<<endl;
Contray_List(L);//參數(shù)n沒用
cout<<"逆置后L:"<<endl;
while(L->next)
{
cout<<L->data<<" -> ";
L=L->next;
if(L->next==NULL)
cout<<L->data;
}
cout<<endl;
cout<<"程序結(jié)束!"<<endl;
} //main
- 1 回答
- 0 關(guān)注
- 167 瀏覽