Status GetElem_L(LinkList L, int i, ElemType &e){ // L是带头结点的链表的头指针,以 e 返回第 i 个元素 p = L->next; int j = 1; while(j != i && p){ p = p->next; j ++; } if(j > i || !p) return ERROR; e = p->data; return OK; } // GetElem_L
在指定位置 i 插入元素:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Status ListInsert_L(LinkList L, int i, ElemType e){ // L 为带头结点的单链表的头指针,本算法 // 在链表中第i 个结点之前插入新的元素 e p = L->next; int j = 1; while(p && j != i - 1){ p = p->next; j ++; } if(!p || j > i - 1) return ERROR; //这里有个问题!!!!!!!!!!!!!!!!!!!!!! s->data = e; s->next = p->next; p->next = s; return OK; } // LinstInsert_L
删除指定位置 i 的元素:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Status ListDelete_L(LinkList L, int i, ElemType &e){ // 删除以 L 为头指针(带头结点)的单链表中第 i 个结点 p = L->next; int j = 1; while(p && j != i - 1){ p = p->next; j ++; } if(!p || j > i - 1) return ERROR; q = p->next; e = q->data; p->next = q->next; free(q); //记得释放结点!!! return OK; } // ListDelete_L
将链表置为空:
1 2 3 4 5 6 7 8 9 10 11
voidClearList(&L){ // 将单链表重新置为一个空表 //这里有问题!!!!!!!!!!!!!!!!记得问.和-> p = L->next; while(p){ L->next = p->next; free(p); p = L->next; } } // ClearList
Status ListInsert_ DuL(DuLinkList &L, int i, ElemType e){ //在带头结点的双链循环线性表L中第i个位置之前插入 //元素e,i的合法值为1≤i≤表长+1. p = L->next; int j = 1; while(p && j < i - 1){ p = p->next; j ++; } if(j >= i - 1 || !p) return ERROR; s = (DuLinkList) malloc(sizeof(DuLNode)); s->data=e; s->prior=p->prior; p->prior->next=s; s->next=p; p->prior=s; return OK; }// ListInsert_ DuL
删除指定位置 i 的元素:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Status ListDelete_ DuL(DuLinkList &L, int i, ElemType &e){ //删除带头结点的双链循环线性表L中第i个 //元素,i的合法值为1≤i≤表长 p = L->next; int j = 1; while(p && j < i - 1){ j ++; p = p->next; } if(p || j >= i - 1) return ERROR; s = p->next; p->next = s->next; s->next->prior = p; e = s->data; free(s); }// ListDelete_ DuL