Trending News
關於資料結構的問題,希望各位高手幫忙
各位好,小弟剛開始自修資料結構C,悟性不高,在書中有一題作業題問說
< C >
For a linked list of integers, create a user-friendly, men-driven program that performs the following
operations.
1. Create a list of integers.
2. Insert an integer at the end of a list.
3. Search for an integer.
4. Delete an integer.
5. Print out a list.
6. Find the length of a list.
請問有哪位可以幫忙給小弟一個完整解答~
謝謝~感激不盡~
2 Answers
- 1 decade agoFavorite Answer
1.
typedef struct node
{
int item;
node* link;
}node;
2.
void addnode()
{
int input;
scanf("%d",&input);
new_node=(node*)malloc(sizeof(node));
new_node->item=input;
if(front == NULL)
{
front=new_node;
new_node->link=NULL;
}
else
{
for(pri=front; pri->link!=NULL; pri=pri->link) ;
new_node->link=pri->link;
pri->link=new_node;
}
}
3.
void searchnode(int x)//這個函式是我臨時打的,沒有編譯過,正確性不明。
{
node search;
search->link=front;
while(search->item!=x)
{
if(search->link==NULL)
{
printf("找不到!");
break;
}
else
search=search->link;
}
}
4.
void del(int x)//其實這個del本身就有search的功能
{
node *n,*p;
n=(node*)malloc(sizeof(node));
n->link=front;
while( (n->link!=NULL) && (n->item!=x) )
{
p=n;
n=n->link;
}
if(n==front && n!=NULL)
{
front=n->link;
free(n);
}
else
{
if(n!=NULL)
{
p->link=n->link;
free(n);
}
else
printf("找不到 %d\n",x);
}
}
5.
void print()
{
for(pri=front;pri!=NULL;pri=pri->link)
{
printf("%4d",*pri);
}
printf("\n");
}
6.
void count()//這個還是也是臨時打的,未經編譯,請自行測試
{
int count_node=0;
ptr=front;//假設ptr已宣告過
while(ptr->link!=NULL)
{
count_node++;
}
printyf("%d",count_node);
}
裡面有些函式是我以前打的,我把它們COPY下來,可能用的方法很土,但應該都很容易理解
有問題的話...找的到我就問吧(雖然我現在已經不常上即時或知識+ XD")
2010-04-18 12:57:50 補充:
我的回答 裡面有些變數沒定義,就當我已宣告在Global,字數很長的大概都是node型態
2010-04-18 13:00:23 補充:
最後一行的"printyf "
不要懷疑!!的確是手誤!!
就說我沒經過編譯=3=
2010-04-19 19:03:17 補充:
的確,我上面"有些"有註明是我臨時打的,我沒編譯過,所以正確性我不清楚
但我沒註明是臨時打的我都有經過編譯,程式都是OK的,畢竟這是我之前的作業,程式是能跑的,至於更高竿的手法,我不會,我想發問者也不一定看的懂,至少我完全是照概念下去打的,有認真一行一行看的人應該都會發現確實如此
謝謝Wu大的指正,我會改進,以後盡量不要犯同樣的錯^^"
Source(s): 自己 - WuLv 51 decade ago
回答者001的回答是太粗糙罷!一些語法錯誤, 一些記憶體陷阱。
2010-04-19 23:10:52 補充:
明白。但我個人覺得,這是態度問題。發問者不懂才問,但如回答者如自己也不確定答案是對的,那你期望發問者可得到什麼?還是你期望發問者可有能力找出你程式的錯處?如第三題,定義node search 卻把 search 當 pointer 來用,已經語法錯誤!只要用編譯器測試一下便知道了,如沒有時間確定,便不要回答便是。也不要什麼高竿低竿的回答,只要正確和可解決題問者問題便成.正如第四題,用 malloc 卻不是一定可 free 便造成記憶體陷阱。這也是初學者很難發現的問題!當然還有很多效率問題,卻不是重點所在了!