求解题目(c++)
c语言编写题目求解!!!!!
#include<stdio.h>
int x, y;
int* buffer;
int size;
void Init(int N);
int GetValue(int _x, int _y);
void SetValue(int _x, int _y, int value);
void Move(int direction);
bool CanMove(int direction);
int main()
{
int N;
scanf("%d", &N);
Init(N);
SetValue(x, y, 1);
int direction = 0;
for (int i = 0; i < N*N-1; i++)
{
while (!CanMove(direction))
{
direction++;
direction %= 4;
}
Move(direction);
SetValue(x, y, i + 2);
}
for (int p = 0; p < N; p++)
{
for (int q = 0; q < N; q++)
{
printf("%4d", GetValue(q, p));
}
printf("\n");
}
return 0;
}
void Init(int N)
{
x = 0; y = 0;
buffer = new int[N*N];
for (int i = 0; i < N*N; i++)
buffer[i] = 0;
size = N;
}
int GetValue(int _x, int _y)
{
return buffer[_y*size + _x];
}
void SetValue(int _x, int _y, int value)
{
buffer[_y*size + _x] = value;
}
void Move(int direction)
{
switch (direction)
{
case 0:
x++;
break;
case 1:
y++;
break;
case 2:
x--;
break;
case 3:
y--;
break;
}
}
bool CanMove(int direction)
{
switch (direction)
{
case 0:
if (x >= size - 1 || GetValue(x + 1, y) > 0)
return false;
return true;
case 1:
if (y >= size - 1 || GetValue(x , y+1) > 0)
return false;
return true;
case 2:
if (x <=0 || GetValue(x - 1, y) > 0)
return false;
return true;
case 3:
if (y <= 0 || GetValue(x , y-1) > 0)
return false;
return true;
}
}
C语言一道题目,求解
C语言一道题目,求解
悬赏分:0 - 离问题结束还有 14 天 23 小时
题目是:把一个链表按反序排序,即将原链头当作链尾,原链尾当作链头。将链表的数据保存在文中,并能读取出来,用函数实现。
我把程序写成如下了,可是为什么保存不了呢?请大虾指教并改成符合题目的程序:
#include "stdio.h"
#include<malloc.h>
struct stu
{
int num;
struct stu *next;
};
void main()
{
FILE *in,*out;
char infile[100],outfile[100];
printf("Enter the infile name:\n");
scanf("%s",infile);
printf("Enter the outfile name:\n");
scanf("%s",outfile);
if((in=fopen(infile,"r"))==NULL)
{
printf("cannot open infile\n");
exit(0);
}
if((out=fopen(outfile,"w"))==NULL)
{
printf("cannot open outfile\n");
exit(0);
}
{
int len=1,i;
struct stu *p1,*p2,*head,*new,*newhead;
p1=p2=head=(struct stu *) malloc(sizeof(struct stu));
printf("input number(0:list end):");
scanf("%d",&p1->num);
while(p1->num!=0)
{
p1=(struct stu *)malloc(sizeof(struct stu));
printf("input number(0:list end):");
scanf("%d",&p1->num);
if(p1->num==0)
p2->next=NULL;
else
{
p2->next=p1;
p2=p1;
len++;
}
}
p1=head;
printf("\noriginal list:\n");
do
{
printf("%4d",p1->num);
if(p1->next!=NULL);
p1=p1->next;
}while(p1->next!=NULL);
printf("%4d",p1->num);
for(i=0;i<len;i++)
{
p2=p1=head;
while(p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(i==0)
newhead=new=p1;
else
new=new->next=p1;
p2->next=NULL;
}
printf("\n\new list:\n");
p1=newhead;
for(i=0;i<len;i++)
{
printf("%4d",p1->num);
p1=p1->next;
}
printf("\n");
}
while(! feof(in)) fputc(fgetc(in),out);
fclose(in);
fclose(out);
}