您的位置:首页 > 其它

双向链表的基本操作

2016-03-29 10:56 218 查看
#include <stdio.h>
#include <stdlib.h>

struct DLinklist{
char data;
struct DLinklist *prior,*next;
};

DLinklist * createDL(){
DLinklist * head,*p;
char x;
head = (DLinklist *)malloc(sizeof(DLinklist));
head->next = head;
head->prior = head;
printf("please input the values!\n");
scanf("%c",&x);
while(x != '\n'){
p = (DLinklist *)malloc(sizeof(DLinklist));
p->data = x;
p->next = head->next;
p->prior = head;
head->next->prior = p;
head->next = p;
scanf("%c",&x);
}
return head;
}

DLinklist * getLocation(DLinklist * head,int i){
DLinklist * p = head;
int j=0;
while(p->next != head && j<i){
j++;
p = p->next;
}
if(p->next != head){
return p;
}else{
return NULL;
}
}

void insertDL(DLinklist * head,int i,char x){
DLinklist * p,*q;
p = getLocation(head,i-1);
if(p == NULL){
printf("the location doesn't exist!\n");
}else{
q=(DLinklist *)malloc(sizeof(DLinklist));
q->data = x;
q->next = p->next;
q->prior = p;
p->next->prior = q;
p->next = q;
}
}

void delDL(DLinklist * head,int i){
DLinklist * p;
p = getLocation(head,i);
if(p == NULL){
printf("the location doesn't exist!\n");
}else{
p->prior->next = p->next;
p->next->prior = p->prior;

free(p);
}
}

void printDL(DLinklist * head){
DLinklist * p;
p = head->next;
while(p != head){
printf("%c",p->data);
p = p->next;
}
}

int main(){
DLinklist * head,*p;
head = createDL();
printDL(head);
printf("\n");

p = getLocation(head,3);
if(p == NULL){
printf("the location doesn't exist!\n");
}else{
printf("%c",p->data);
}
printf("\n");

printf("after insert:\n");
insertDL(head,5,'a');
printDL(head);
printf("\n\n");

printf("after delete:\n");
delDL(head,4);
printDL(head);
printf("\n");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: