1.链式表的按序号查找
本题要求实现一个函数,找到并返回链式表的第K个元素。
#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
typedef int ElementType;
typedef struct LNode *PtrToLNode;
struct LNode {
ElementType Data;
PtrToLNode Next;
};
typedef PtrToLNode List;
List Read(); /* 细节在此不表 */
ElementType FindKth( List L, int K );
int main()
{
int N, K;
ElementType X;
List L = Read();
scanf("%d", &N);
while ( N-- ) {
scanf("%d", &K);
X = FindKth(L, K);
if ( X!= ERROR )
printf("%d ", X);
else
printf("NA ");
}
return 0;
}
ElementType FindKth(List L,int K){
List p=L;
int i;
for(i=1;p!=NULL;i++){
if(i==K)
return p->Data;
else p=p->Next;
}
return ERROR;
}
2.单链表逆转
本题要求实现一个函数,将给定的单链表逆转。
第一种:
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表 */
List Reverse( List L );
int main()
{
List L1, L2;
L1 = Read();
L2 = Reverse(L1);
Print(L1);
Print(L2);
return 0;
}
List Reverse( List L ){
List L1=(List)malloc(sizeof (List));
L1->Next=NULL;
List p=L;
List a;
List q=L1;
while(p!=NULL){
a=(List)malloc(sizeof (List));
a->Data=p->Data;
a->Next=q->Next;
q->Next=a;
p=p->Next;
}
L1=L1->Next;
return L1;
}
第二种:
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode List;
List Read(); /* 细节在此不表 */
void Print( List L ); /* 细节在此不表 */
List Reverse( List L );
int main()
{
List L1, L2;
L1 = Read();
L2 = Reverse(L1);
Print(L1);
Print(L2);
return 0;
}
List Reverse( List L ){
List p=L;
List q;
L=NULL;
while(p){
q=p;
p=p->Next;
q->Next=L;
L=q;
}
return L;
}
这道题一开始我用的方法是再重新定义一个链表,然后把L逆转过来,但是后来发现这样不符合题意,输出结果不对,而且时间复杂度高。用的第二种方式显然会更简洁。
使用第一种方法时还出现了运行结果的第一项会多出一个0 的现象,后来发现是因为自己设置的变量出了问题,在最后移动一下指针就能解决。
用天平找小球
三个球A、B、C,大小形状相同且其中有一个球与其他球重量不同。要求找出这个不一样的球。
输入格式:
输入在一行中给出3个正整数,顺序对应球A、B、C的重量。
#include<stdio.h>
int main(){
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
if(a==b){
printf("C");
}
if(c==b){
printf("A");
}
if(a==c){
printf("B");
}
}
链表的内容确实有些模糊了,不过边写代码边复习些数据结构的内容感觉很不错,明天也会继续写链表的内容!