单链表的基本操作
来源:互联网 发布:北美海关数据 编辑:程序博客网 时间:2024/06/14 01:08
基本操作的声明:
typedef struct Node{ int data;//数据 struct Node *next;//指向下一个结点}Node, *List;//对单链表的操作void InitList(List plist);//初始化单链表bool Insert_head(List plist, int val);//头插法bool Insert_tail(List plist, int val);//尾插法bool Insert_pos(List plist, int pos, int val);//pos位置插入Node *Search_pre(List plist, int key);//查找key的前驱bool Delete(List plist, int key);//删除key这个结点bool IsEmpty(List plist);//是否为空void Destroy(List plist);//摧毁函数(如果有动态开辟内存)int GetLength(List plist);//得到单链表的长度void Show(List plist);//打印单链表void Reverse(List plist);//逆置单链表
基本操作的定义:
void InitList(List plist){ assert(plist != NULL); if (plist == NULL) { return; } plist->next = NULL;}static Node *GetNode(int val){ Node *p = (Node *)malloc(sizeof(Node)); assert(p != NULL); p->data = val; p->next = NULL; return p;}bool Insert_head(List plist, int val){ Node *pGet = GetNode(val); pGet->next = plist->next; plist->next = pGet; return true;}bool Insert_tail(List plist, int val){ Node *p; for (p = plist;; p = p->next) { if (p->next == NULL) { break; } } Node *pGet = GetNode(val); p->next = pGet; return true;}int GetLength(List plist){ int count = 0; for (Node *p = plist; p->next != NULL; p = p->next) { count++; } return count;}bool Insert_pos(List plist, int pos, int val){ if (pos < 0 || pos > GetLength(plist) + 1) { return false; } Node *p = plist; for (int i = 0; i <= pos - 1; i++) { p = p->next; } Node *pGet = GetNode(val); pGet->next = p->next; p->next = pGet; return true;}Node *Search_pre(List plist, int key){ Node *p; for (p = plist; p->next != NULL; p = p->next) { if (p->next->data == key) { return p; } } return NULL;}bool Delete(List plist, int key){ Node *p = Search_pre(plist, key); if (p == NULL) { return false; } Node *q = p->next; p->next = q->next; free(q); q = NULL; return true;}bool IsEmpty(List plist){ if (plist == NULL) { return true; } return false;}void Destroy(List plist){ Node *p; while (plist->next != NULL) { p = plist->next; plist->next = p->next; free(p); } p = NULL;}void Show(List plist){ Node *p; for (p = plist->next; p != NULL; p = p->next) { printf("%d ", p->data); } printf("\n");}void Reverse(List plist){ Node *p, *q; p = plist->next; plist->next = NULL; while (p) { q = p; p = p->next; q->next = plist->next; plist->next = q; }}
主函数测试功能:
int main(){ Node head; InitList(&head); for (int i = 0; i < 10; i++) { //Insert_head(&head,i); Insert_tail(&head, i); } Show(&head); Insert_pos(&head, 0, 19); Show(&head); int n = GetLength(&head); printf("%d\n",n); Delete(&head,6); Show(&head); Node *q=Search_pre(&head,7); printf("%d\n",q->data); Reverse(&head); Show(&head); //Destroy(&head); return 0;}
阅读全文