刪除指定結點
流程:判斷傳入數據和pos的位置是否符題意——找到刪除位置的前一個結點,找到后要判斷所找的位置是否越界——刪除指定結點。代碼:
//刪除指定結點
int Delete_Pos(Node* h, int pos)
{if (NULL == h || pos < 1){return FALSE;}Node* tmp = h;int i;for (i = 0; i < pos - 1; i++){if (NULL == tmp->next){break;}tmp = tmp->next;}if (NULL == tmp){printf ("刪除位置越界");return FALSE;}Node* p = tmp->next;tmp->next = p->next;free(p);return TRUE;
}
和頭指針的區別:不需要考慮空表的情況。
逆序
流程:先后判斷傳入數據是否正確,是否為空表,是否只有一個結點——從前往后,3個為一組,將前兩個指向調換,以此為循環向后遍歷直到結束,結束標志為一組中第二個為NULL——最后一步,將逆序后的最后一個指向NULL,頭指針 h 指向逆序后的第一個。(原理和頭指針一樣,由于頭結點的存在導致代碼略有不同)
代碼:
//逆序
int Reverse_List(Node* h)
{if (NULL == h || NULL == h->next|| NULL == h->next->next){return FALSE;}Node* pre = h->next;Node* cur = h->next->next;Node* tmp;while (cur){ tmp = cur->next;cur->next = pre;pre = cur;cur = tmp;}//最終操作略有差異h->next->next = NULL; h->next = pre;return TRUE;
}
刪除數據
流程:判斷傳入數據的準確性——保存頭結點的地址,尋找所要刪除的數據,并記錄下tmp->next——判斷記錄的是否為空,不為空則刪除那個結點
代碼:
//刪除數據
int Delete_Data(Node* h, LinkData data)
{if (NULL == h){return FALSE;}Node* tmp = h;while (tmp->next){if (data == tmp->next->data){break;}tmp = tmp->next;}if (NULL == tmp->next){return FALSE;}Node* p = tmp->next;tmp->next = p->next;free(p);return TRUE;
}
查找元素
流程:判斷傳入數據是否正確——保存第一個結點的地址,遍歷知道找到所要找的元素,保存下標。沒找到則返回FALSE。代碼:
//尋找元素
int Find_Element(Node* h, LinkData data, int* x)
{if (NULL == h){return FALSE;}Node* tmp = h->next;int k = 1;while (tmp){if (data == tmp->data){*x = k;}k++;tmp = tmp->next;}return FALSE;
}
獲取順序表中的元素:通過位置獲取
流程:判斷傳入數據的準確性——遍歷到pos位置處,將pos處的數據保存到*x中。代碼:
// 獲取順序表中的元素:通過位置獲取
int Get_Element(Node* h, int pos, int *x)
{if (NULL == h || pos < 1){return FALSE;}Node* tmp = h;int i;for (i = 0; i < pos; i++){if (NULL == tmp){break;}tmp = tmp->next;}//判斷tmp是否為空if (NULL == tmp){return FALSE;}else{*x = tmp->data;}return TRUE;
}
獲取長度
流程:判斷傳入數據是否正確——從第一個節點遍歷到最后一個結點,計算共有多少結點。代碼:
//獲取長度
int Get_Len(Node * h)
{if (NULL == h){return FALSE;}int count = 0;Node* tmp = h;while (tmp->next){count++;tmp = tmp->next;}return count;
}
清除列表
流程:利用Delete_Pos一個一個清除。代碼:
int Clean_List(Node * h)
{if (NULL == h){return FALSE;}Node *tmp = h;while (tmp->next){Delete_Pos(h, 1);}return 0;
}
輸出顯示
// 輸出顯示
void Display(Node *h)
{if (NULL == h){return;}int count = 0;Node *tmp = h->next;while (tmp){printf (++count % 4 ? "%8d" : "%8d\n", tmp->data);tmp = tmp->next;}printf ("\n");
}
銷毀鏈表
原理:利用Clean_List銷毀,最后要釋放空間,防止內存泄露
//銷毀鏈表
int Destroy(Node *h)
{if (NULL == h){return FALSE;}Clean_List(h);free(h);return TRUE;
}