【发布时间】:2014-04-09 14:13:09
【问题描述】:
我正在尝试使用链表来增强我对指针的概念。
我已经成功创建了链表,它也给出了最少两个元素,但我尝试了元素的数量来测试它。
突然我发现它不适用于以下示例:
enter the size of node
4
start entering the number of elements until your size
6
1
7
59
Printing linked list
6-> 1-> 7-> 59->
The two minimumnumbers are min1 :1 and min2 : 1
我这样做的完整代码是:可以直接切换到函数find_two_min()
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
struct node
{
int freq;
struct node * next;
};
typedef struct node node;
node * tree;
//Problem creating area is below (code for finding minimum two elements)
void find_two_min(node**List,node** lmin1,node** lmin2)
{
node*temp=*List;
node*min1,*min2;
node*var1=*List;
node* second=(*List)->next;
if(var1>second)
{
min2=var1;
min1=second;
}
else
{
min1=var1;
min2 =second;
}
while(temp!=NULL)
{
if(temp->freq<min2->freq)
{
min1=min2;
min2=temp;
}
else if(temp->freq<min1->freq)
{
min1=temp;
}
temp=temp->next;
}
*lmin1=min1;
*lmin2=min2;
}
void main()
{
int size, data;
node* min1, *min2;
int count = 0; //this count flag is to check is it's first node or not inside the do-while loop.
tree = NULL;
printf("enter the size of node\n");
scanf("%d", & size);
printf("start entering the number of elements until your size\n");
node * prev;
do
{
scanf("%d", & data);
if (count == 0)
{
node * temp;
temp = (node * ) malloc(sizeof(node));
temp-> freq = data;
temp-> next = NULL;
prev = temp;
tree=prev;
}
else
{
node * temp ;
temp = (node * ) malloc(sizeof(node));
temp-> freq = data;
temp-> next = NULL;
prev-> next = temp;
prev=prev->next;
}
size--;
++count;
}
while (size > 0);
printf("Printing linked list\n");
node * temp1;
temp1 = tree;
while (temp1!= NULL)
{
printf("%d-> ", temp1-> freq);
temp1 = temp1-> next;
}
node*temp5=tree;
find_two_min(&temp5,&min1,&min2);
printf("\n The two minimumnumbers are min1 :%d and min2 : %d\n",min1->freq,min2->freq);
}
谁能告诉我为什么它不能在这个特定的例子上工作,而它在其他样本上工作?你能帮我改正吗?
【问题讨论】:
标签: c algorithm data-structures linked-list singly-linked-list