带头结点的单链表基本操作实现
#include#include typedef struct _node { int val; struct _node *next; } Node; typedef struct _list { Node *pHead; int length; } List; void InitList(List *list);//初始化链表 void ClearList(List *pList);//清空链表 int ListEmpty(List list);//链表判空 int ListLength(List list);//返回链表长度 void GetElem(List list, int i, int *e);//根据位置返回值 Node *LocateElem(List list, int e);//根据值返回指向该节点的指针 void ListInsert(List *list, int i, int e);//在位置i上插入值为e的结点 void Delete(List *pList, int i, int *e);//删除位置i上的结点,并用e返回结点值。 int main() { int x; List list; InitList(&list); // Node *node = (Node *)malloc(sizeof(Node)); // node->val = 3; // node->next = NULL; // list.pHead->next = node; printf("%dn", ListLength(list)); ListInsert(&list, 1, 3); Delete(&list, 1, &x); printf("%d %d", ListLength(list), x); return 0; } void InitList(List *pList) { Node *node = (Node *)malloc(sizeof(Node)); node->val = 0; node->next = NULL; pList->pHead = node; } void ClearList(List *pList) { Node *node = pList->pHead->next; if (node) { while (node->next) { Node *temp = node; node = node->next; free(temp); } } pList->pHead->next = NULL; } int ListEmpty(List list) { if (list.pHead->next == NULL) return 1; return 0; } int ListLength(List list) { int len = 0; Node *node = list.pHead; if (ListEmpty(list)) return 0; while (node->next) { len++; node = node->next; } return len; } void GetElem(List list, int i, int *e) { if (ListEmpty(list) || i < 1 || i > ListLength(list)) return; int count = 0; Node *node = list.pHead; while (count != i) { node = node->next; count++; } *e = node->val; } Node *LocateElem(List list, int e) { Node *ret = list.pHead; if (ListEmpty(list)) return NULL; while (ret) { if (ret->val == e) return ret; ret = ret->next; } return NULL; } void ListInsert(List *list, int i, int e) { int j = 0; Node *p = list->pHead; if (i < 1 || i > ListLength(*list) + 1) return; while (j < i - 1) { j++; p = p->next; } Node *node = (Node *)malloc(sizeof(Node)); node->val = e; node->next = p->next; p->next = node; } void Delete(List *pList, int i, int *e) { int j = 0; Node *p, *q; p = pList->pHead; if (i < 1 || i > ListLength(*pList)) return; while (j < i - 1) { p = p->next; j++; } q = p->next; p->next = p->next->next; *e = q->val; free(q); }



