我想实现链表自动删除特定类元素,比如能被三整除的数.
但运行时输入很奇怪,似乎不能输入两位数即以上的数,我不明白是哪里出了问题.
#include
#include
using namespace std;
#include
typedef int Status;
typedef char Elemtype;
typedef struct LNode {//定义链表
Elemtype Data;
//Elemtype* next;
struct LNode *next;
}LNode,*LinkList;
int Inilist(LinkList &L){//初始化链表//int 型
L = new LNode;
L->next = NULL;
return OK;
}
void Create_List(LinkList &L,Elemtype n){
L = new LNode;
L -> next = NULL;
LNode *R = L;
for(int i = 1; i <= n; i++){
LNode *S;
S = new LNode;
cin >> S->Data;
S->next = NULL;
R->next = S;
R = S;
}
}
void Delete(LinkList &L){
LNode *p = L->next;
LNode *Target = L;
while(p){
if(p->Data % 3 == 0){
Target ->next = p->next;//假设第一个就能被三整除
free(p);//释放目标数据
p = Target ->next;
}
else{
Target = p;//不被三整除,就往后挪一个位置继续找
p = p->next;//为下一次循环做准备
}
}
}
void PrintList(LinkList &L){
LNode *P;
P = new LNode;
P = L -> next;
while(P){
cout << P->Data << " ";
P = P->next;
}
cout << endl;
}
int main() {
int n = 0;
LinkList LA;
Inilist(LA);
cin >> n;
Create_List(LA, n);
PrintList(LA);
Delete(LA);
PrintList(LA);
return 0;
}
因为
typedef char Elemtype;
所以链表每个节点只能装下单个字符
#include <stdio.h>
void main()
{
int i,x,y;
int z = 1;
printf("请输入 两个数 X 和 Y ,求出 X^Y 的值:");
scanf("%d %d",&x,&y);
for (i=1;i<=y;i++)
z = z*x%1000;
if (z>=100)
printf("%d^%d 的最后三位是:%d\n",x,y,z);
else if (z<=100)
printf("%d^%d 的最后三位是:0%d\n",x,y,z);
else
printf("%d^%d 的最后三位是:00%d\n",x,y,z);
}
代码分析: 这里 面使用了算术运算符 取余【%】与 取商【/】的技巧 :一个数 分别 使用 取余和取商 是将 该数 分割处理 至于分割点的选取 看被除数 的位数 。拿 20736 来说 被 1000 取余 的结果是:736 取商 的结果是 20