双向链表循环,完成插入删除搜素打印基本功能。
#include<stdio.h>
#include<stdlib.h>
typedef int elemType;
typedef struct listnode{
elemType info;
struct listnode * previous;
struct listnode * next;
}listnode;
listnode * linkListInit(listnode * head){
head = NULL;
return head;
}
listnode * addNode(listnode *head,elemType value){
listnode *ptr = (listnode *)malloc(sizeof(listnode));
ptr->info = value;
if( NULL == head){
ptr->previous = NULL;
ptr->next = NULL;
head = ptr;
return head;
}
if( head->next == NULL){
head->next = ptr;
head->previous = ptr;
ptr->previous = head;
ptr->next = head;
return head;
}
ptr->previous = head->previous;
head->previous->next = ptr;
head->previous = ptr;
ptr->next = head;
return head;
}
listnode * findNode(listnode * head,elemType value){
listnode *ptr = head;
if(NULL == head)//0 elem
return NULL;
else if(NULL == ptr->next){ //1 elem
if(value == ptr->info)
return ptr;
else
return NULL;
}
do{
if(value == ptr->info)
return ptr;
ptr = ptr->next;
}while(ptr != head);
return NULL;
}
listnode * delNode(listnode * head,elemType value){
listnode *elemPtr = findNode(head,value);
listnode *pre,*next;
if(NULL == elemPtr)
printf("Cannot find value: %d in list.\n",value);
else{
if(head->next == NULL){
head = NULL;
free(elemPtr);
}
else if(head->next == head->previous){
if(head == elemPtr){
head = head->next;
head->next = NULL;
head->previous = NULL;
free(elemPtr);
}
else{
head->next = NULL;
head->previous = NULL;
free(elemPtr);
}
}
else{
pre = elemPtr->previous;
next = elemPtr->next;
elemPtr->previous->next = next;
elemPtr->next->previous = pre;
if(elemPtr == head)
head = next;
free(elemPtr);
}
}
return head;
}
void printList(listnode *head){
if(NULL == head){
printf("No elements in list.\n");
return;
}
listnode *ptr = head;
printf("printf from head to rear:\n");
do{
printf("%d -> ",ptr->info);
ptr = ptr->next;
}while(ptr != head && ptr != NULL);
printf("\n");
printf("printf from rear to head:\n");
ptr = head;
if(NULL == ptr->previous){
printf("%d -> \n",ptr->info);
return ;
}
do{
ptr = ptr->previous;
printf("%d -> ",ptr->info);
}while(ptr != head);
printf("\n");
}
int main(){
listnode *head;
int i;
head=linkListInit(head);
for(i=0;i<10;i++){
head=addNode(head,i);
}
printList(head);
head = delNode(head,2);
printList(head);
head = delNode(head,0);
printList(head);
return 0;
}
微信扫一扫,订阅我的博客动态^_^