单链表的操作
#include "stdafx.h" #include<iostream> using namespace std; typedef int ElemType; typedef enum Status { success, fail, fatal, rangeerror, overflow }Status; typedef struct node { ElemType data; //数据域 struct node * next; //指针域 }ListNode,*ListNodePtr; typedef ListNodePtr List, *ListPtr; Status List_Init(ListPtr L) { Status status = fatal; *L = (ListNodePtr)malloc(sizeof(ListNode));/*分配存储空间*/ if (*L) { (*L)->next = NULL; status = success; } return status; } void List_Clear(ListPtr L) { ListNodePtr p = *L; ListNodePtr q = p->next; while (q) { p->data = q->data; free(q); q = p->next; } } void List_Destroy(ListPtr L) { List_Clear(L); free(L);//删除头节点 } bool List_Empty(ListPtr L) { return (*L)->next == NULL; } int List_Size(ListPtr L) { int length = 0; ListNodePtr p = (*L)->next; while (p) { length++; p = p->next; } return length; } Status List_SetPosition(ListPtr L, int pos, ListNodePtr * ptr) { Status status = fail; ListNodePtr p = *L; int i = 0; while (ptr && i < pos) { i++; p = p->next; } if (p && i == pos) { *ptr = p; status = success; } return status; } Status List_Prior(ListPtr L, int pos, ElemType *elem) { Status status = fail; ListNodePtr ptr; status = List_SetPosition(L, pos - 1, &ptr); if (status == success) { *elem = ptr->data; } return status; } Status List_Next(ListPtr L, int pos, ElemType *elem) { Status status = fail; ListNodePtr ptr; status = List_SetPosition(L, pos + 1, &ptr); if (status == success) { *elem = ptr->data; } return status; } Status List_Insert(ListPtr L, int pos, ElemType elem) { Status status = fail; ListNodePtr ptr, s; status = List_SetPosition(L, pos - 1, &ptr); if (status == success) { s = (ListNodePtr)malloc(sizeof(ListNode)); } if (s) { s->data = elem; s->next = ptr->next; ptr->next = s; } else { status = fail; } return status; } Status List_Remove(ListPtr L, int pos) { Status status = fail; ListNodePtr ptr; status = List_SetPosition(L, pos - 1, &ptr); if (status == success) { ptr->next = ptr->next->next; free(ptr->next); } return status; } Status List_Create(ListPtr L, ElemType elem[], int n) { Status status = success; ListNodePtr p, q; int i = n - 1; q = (ListNodePtr)malloc(sizeof(ListNode)); q->next = NULL; while (i >= 0) { p = (ListNodePtr)malloc(sizeof(ListNode)); if (!p) { status = fatal; break; } p->data = elem[i]; p->next = q->next; q->next = p; i--; } *L = q; return status; }