#include<stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct POINT
{
int row;
int col;
struct POINT *next;
}POINT;
void initPointLink(POINT **pointLinkHeadPointer);
void showPoints(POINT *pointLinkHead);
void showOnePoint(POINT onePoint);
void destroyPointLink(POINT **pointLinkHeadPointer);
void insertPointToLink(POINT **pointLinkHeadPointer);
POINT *searchPreToPoint(POINT *h, POINT old);
void changePointValue(POINT *point, int row, int col);
POINT *makeOnePoint(int row, int col);
POINT *makeOnePoint(int row, int col)
{
POINT *p;
p = (POINT *)malloc(sizeof(POINT));//申请新的节点
p->row = row;
p->col = col;
p->next = NULL;
return p;
}
void changePointValue(POINT *point, int row, int col)
{
point->row = row;
point->col = col;
}
POINT *searchPreToPoint(POINT *h, POINT old)
{
POINT *q = NULL;
for(; h&&(h->row != old.row||h->col != old.col); h = h->next)
q = h;
return q;
//查找将会有以下几种情况:
//1、没有找到,也就是遍历完真个链表,压根就不存在要找的点,那么他将会返回最后一个点的链域,即q->next=NULL
//2、找到的点就是第一个节点,那么将会返回一个q==NULL的值;
//3、要找的点就是找到了,切返回值应该及时我们要找的节点的前驱结点
//根据以上分析,该函数是有返回值的,返回值的类型
}
void insertPointToLink(POINT **hp)
{
POINT *pre; //指向要插入位置点的前驱结点
POINT *p; //指向新点
POINT oldPoint; //要插入位置的点,
int newRow;
int newCol;
int oldRow;
int oldCol;
// printf("\n当前点信息如下:\n");
showPoints(*hp);
printf("\n");
printf("请输入新点坐标:\n");
scanf("%d%d", &newRow, &newCol);
printf("请输入要插入的位置的点坐标(若该点不存在则追加在链表末尾):\n");//再考虑,该点不存在返回插入失败
scanf("%d%d", &oldRow, &oldCol);
changePointValue(&oldPoint, oldRow, oldCol);
oldPoint.next = NULL;
pre = searchPreToPoint(*hp, oldPoint);
p = makeOnePoint(newRow, newCol);
p->next = NULL;
if(pre = NULL)
{
p->next = *hp; //头插
*hp = p;
}
else
{
p->next = pre->next; //运行到这里的时候,程序崩溃,不只是什么原因?
pre->next = p;
}
//若要插入一个点,那么首先得找到插入的位置的点坐标。也就是找到该点的前驱节点
//那么继续编写一个找寻前驱结点的函数searchPreToPoint();
}
void destroyPointLink(POINT **h)
{
POINT *p;
while(*h)
{
p = *h;
*h = p->next;
free(p);
}
}
void showOnePoint(POINT p)
{
printf("<%d, %d> ", p.row, p.col); //若有多处显示,并且要改动显示型式,那么只需要改动函数里边即可
}
void showPoints(POINT *h)
{
POINT *p;
printf("\n当前点坐标如下:\n");
for(p = h; p; p = p->next)
showOnePoint(*p);
}
void initPointLink(POINT **h)
{
POINT *p; //用来指向申请到的神节点
POINT *q; //用来指向末节点
int row;
int col;
if(*h) //如果链表在使用前非空,那么将要清空链表
destroyPointLink(h);
//如何清空链表?
//1、*h != NULL条件成立,即,找到末节点,然后free();即可。
printf("请输入点的坐标:例如:3 4.注意:任意坐标值为0时,结束输入:");
scanf("%d%d", &row, &col);
while(row&&col) //只要任意坐标不为0,就继续录入点的坐标
{
p = makeOnePoint(row, col);
//完成上边的申请新的节点之后。考虑:如何将这些点串成链表?
//1、如何链表为空那么直接让头指针指向申请到的节点;
//2、如果链表不为空,那么则将申请到的新的节点追加在原来的节点的后面
if(*h==NULL)
*h = p;
else
q->next = p;
q = p;
printf("请输入点的坐标:例如:3 4.注意:任意坐标值为0时,结束输入:");
scanf("%d%d", &row, &col);
}
}
void main(void)
{
POINT *Head1 = NULL; //产生一个空链表
initPointLink(&Head1);
showPoints(Head1);
insertPointToLink(&Head1);
showPoints(Head1);
destroyPointLink(&Head1);
showPoints(Head1);
getch();
// system("pause");
}