(1)查找元素并删除
int findAndDelete(LNode *list, int x){
//先找到该元素
LNode *p;
p = list;
while(p->next != NULL){
if(p->next == x){
break;
}
p = p->next;
}
//然后删除
if(p->next == NULL){
return 0;
}
else{
LNode *del;
del = p->next;
p->next = p->next->next;
free(del);
return 1;
}
}
(2)删除单链表中的最小值
void deleteMin(LNode *list){
//p扫描链表,pre指向p的前驱
//minp用来指向最小值结点,premin指向minp的前驱
LNode *p = list->next, *pre = list; *premin = pre;
while(p != MULL){
if(p->data < minp->data){
minp = p;
premin = pre;
}
pre = p;
p = p->next;
}
premin->next = minp->next;
free(minp);
}
(3)查找链表中倒数第k个结点
int findkLast(LNode *list,int k){
LNode *p, *q;
p = list->next;
q = list;
int i = 1;
while(p != NULL){
p = p->next;
i++;
if(i > k)
q = q->next;
}
if(q == list) //链表的结点不到k个
return 0;
else{
printf("%d",q->data);
return 1;
}
}
(4)尾插法建立双链表
typedef struct DLNode{
int data;
struct DLNode *prior;
struct DLNode *next;
}DLNode;
void createDListR(DLNode *&list, int a[], int n){
//准备工作
DLNode *s, *r;
list = (DLNode *)malloc(sizeof(DLNode));
list->prior = NULL;
list->next = NULL;
r = list;
//开始插入元素
int i;
for(int i=0; i<n; i++){
s = (DLNode *)malloc(sizeof(DLNode));
s->data = a[i];
//尾插法
r->next = s;
s->prior = r;
r = s;
}
r->next = NULL; //如果不加这句话,一定会出事的!!!
}
(5)查找结点的算法
typedef struct DLNode{
int data;
struct DLNode *prior;
struct DLNode *next;
}DLNode;
DLNode* findNode(DLNode *list, int x){
DLNode *p = list->next;
while(p != NULL){
if(p->data == x)
break;
p = p->next;
}
return p;
}
(6)插入结点的算法
int insertNode(DLNode *&list, int index, int e){
if(index < 0) return 0;
DLNode *p = list;
for(int i=0; i<index; i++){
p = p->next;
}
DLNode *s = (DLNode *)malloc(sizeof(DLNode));
s->data = e;
//插入
s->next = p->next;
s->prior = p;
p->next = s;
s->next->prior = s;
return 1;
}
(7)删除结点的算法
int deleteNode(DLNode *&list, int index){
DLNode *p = list;
for(int i=0; i<index; i++){
p = p->next;
}
if(p->next == NULL)
return 0;
DLNode *del;
del = p->next;
p->next = del->next;
if(del->next != NULL){ //不加这个会出事
del->next->prior = p;
}
free(del);
return 1;
}