双向链表实例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
int item;
struct node *next;
struct node *prev;
}node;
//插入
int list_insert(node **list)
{
int ret = 0;
node *newnode = malloc(sizeof(node));
memset(newnode, 0x00, sizeof(newnode));
if ( newnode == NULL )
ret = -1;
if ( ret != -1 ) {
printf("item: ");
scanf("%d", &newnode->item);
newnode->next = newnode->prev = NULL;
if ( *list == NULL ) {
*list = newnode;
newnode->next = newnode;
newnode->prev = newnode;
} else {
newnode->next = *list;
newnode->prev = (*list)->prev;
(*list)->prev->next = newnode;
(*list)->prev = newnode;
}
}
return ret;
}
//删除
node *list_delete(node **list, int pos)
{
node *ret = NULL;
if ( *list!=NULL && pos>=0 ) {
int i;
node *cur = *list;
node *prev = NULL;
for (i=0; i<pos; i++) {
prev = cur;
cur = cur->next;
}
if ( prev == NULL ) {
if ( cur == cur->next ) { //只有一个节点,然后删除
*list = NULL;
} else if ( cur != NULL ) { //有好多节点,然后删除第一个,
(*list)->prev->next = cur->next;
cur->next->prev = (*list)->prev;
*list = cur->next;
}
ret = cur;
} else {
ret = cur;
cur->next->prev = prev;
prev->next = cur->next;
}
}
return ret;
}
//显示
void list_display( node *list )
{
node *cur = list;
if ( cur != NULL ) {
do {
printf("%d ", cur->item);
cur = cur->next;
} while ( cur != list );
}
return;
}
int main( void )
{
node *list = NULL;
list_insert(&list);
list_insert(&list);
list_insert(&list);
list_insert(&list);
while ( list != NULL ) {
printf("%d ", list_delete(&list, 0)->item);
}
printf("\n");
}