包含双向链表的创建,插入,遍历,查找,排序,删除,销毁。
#include <stdio.h>
typedef struct node
{
int data;
struct node *next;
struct node *pre;
}Node;
Node *creatList()
{
Node *head = (Node*)malloc(sizeof(Node));
head->next = head;
head->pre = head;
return head;
}
void inseartList(Node *head,int data)
{
Node *cur = (Node*)malloc(sizeof(Node));
cur->data = data;
cur->next = head->next;
head->next = cur;
cur->pre = head;
cur->next->pre = cur;
}
void traverlist(Node *head)
{
Node *phead = head->next;
while (phead != head)
{
printf("%d\n",phead->data);
phead = phead->next;
}
}
int strlenlist(Node *head)
{
int len = 0;
Node *phead = head->next;
while(phead != head)
{
len++;
phead = phead->next;
}
return len;
}
Node *searchlist(Node *head, int find)
{
Node *phead = head->next;
while(phead != head)
{
if(phead->data == find)
return phead;
phead = phead->next;
}
return NULL;
}
Node *doublesearchlist(Node *head,int data)
{
Node *pdowm = head->next;
Node *pup = head->pre;
while(pdowm->pre != pup)
{
if(pdowm->data == data)
return pdowm;
if(pup->data == data)
return pup;
if(pdowm == pup)
return NULL;
pdowm = pdowm->next;
pup = pup->pre;
}
return NULL;
}
void deletelist(Node *pfind)
{
if(pfind == NULL)
return ;
else
{
pfind->next->pre = pfind->pre;
pfind->pre->next = pfind->next;
free(pfind);
}
}
void destrylist(Node *head)
{
head->pre->next = NULL;
Node *pre = head;
while(head)
{
head = head->next;
free(pre);
pre = head;
}
}
void sqrtlist(Node *head,int n)
{
Node *q;
Node *p;
for(int i=0;i<n-1;i++)
{
q = head->next;
p = q->next;
for(int j=0;j<n-1-i;j++)
{
if(p->data < q->data)
{
p->data ^= q->data;
q->data ^= p->data;
p->data ^= q->data;
}
q = q->next;
p = p->next;
}
}
}
int main(int argc, char *argv[])
{
Node *head = creatList();
for(int i= 0;i<10;i++)
{
inseartList(head,i);
}
sqrtlist(head,10);
traverlist(head);
printf("---------------------------\n");
printf("%d\n",strlenlist(head));
Node *pfind = doublesearchlist(head,5);
printf("%d\n",pfind->data);
deletelist(pfind);
traverlist(head);
destrylist(head);
printf("Hello World!\n");
return 0;
}