#include
#include
#include
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);
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();
}
插入函數裡的”if(pre = NULL)“,注意等號!!!!!!!!!!!!!!!!!!!!!!!!!!!