指针问题,写了一会错了求解答
. 使用指针编程实现输入n个整数,统计不同数字的个数。输入示范
Input n:10
Input nums:20 15 30 20 15 30 78 78 56 92
输出示范
6
程序代码:#include <stdio.h>
int main()
{
int a[10]={20,15,30,20,15,30,78,78,56,92};
int i,j,k=1,tmp;
for(i=0;i<9;i++)
{
for(j=i+1;j<10;j++)
{
if(a[i]>a[j])
{
tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
}
}
for(i=1;i<10;++i)
{
k++;
if(a[i]==a[i-1]) k--;
}
printf("%d\n",k);
return 0;
}

程序代码:
#include<stdio.h>
#include<malloc.h>
void main()
{
int i,j,n,*pt,*pt1;
while(1)
{
printf("Input n:");
scanf("%d",&n);
pt1=(int *)malloc(n*sizeof(int));
pt=pt1;
printf("Input %d nums:",n);
for(i=0;i<n;i++)
scanf("%d",pt1++);
pt1=pt;//pt1指针复位
for(i=0;i<n;i++)
printf("%6d",*pt1++);
pt1=pt;//pt1指针复位
printf("\n");
if(n==1)
printf("1");
else
{
//时间有限,未完成,按楼上大神类似的先排序再计算不同的个数
}
free(pt);
}
}
程序代码:#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN sizeof(Node)
typedef struct Node
{
int num;
struct Node *next;
struct Node *back;
}Node;
Node *head=NULL;
int n=0;
void insert(Node *p1,Node *p2)
{
if (p1==head)
{
p2->next=head;
p2->back=NULL;
head->back=p2;
head=p2;
return;
}
p2->back=p1->back;
p1->back->next=p2;
p2->next=p1;
p1->back=p2;
return;
}
void fun(int a)
{
Node *p=head;
Node *p2=NULL;
if (head==NULL)
{
p=head=(Node *)malloc(LEN);
head->next=NULL;
head->back=NULL;
head->num=a;
n++;
return ;
}
while (p->num>a&&p->next)
p=p->next;
if (p->num==a)
return ;
n++;
p2=(Node *)malloc(LEN);
p2->num=a;
if (p->num>a)
{
p->next=p2;
p2->back=p;
p2->next=NULL;
return ;
}
insert(p,p2);
}
int main()
{
long int a[]={11111111,22222222,33333333,33333333,44444444,11111111,22222222};
int *p=a;
for (;p-a<sizeof(a)/sizeof(int);++p)
fun(*p);
printf("共有%d个不重复的数字\n",n);
return 0;
}
