联系方式:lichunwen1987 AT qq DOT com
找工作,各种数据结构和算法问题,写个双向循环链表练习联系吧
/*带头结点顺序双向循环链表*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
#define N_RAND 200
typedef struct Node {
int key;
struct Node * pre;
struct Node * next;
}Node, *PNode;
//初始化单个结点
PNode IniNode(int key){
PNode q=(PNode)malloc(sizeof(Node));
q->key=key;
q->next=NULL;
q->pre=NULL;
}
//初始化循环链表,设置头结点
void IniLink(PNode *h){
PNode hNode=IniNode(-1);
*h=hNode;
//初始化头结点指向自身
hNode->next=hNode;
hNode->pre=hNode;
}
void InsertElem(PNode *h, int key){
PNode p=(*h)->next;
PNode q=IniNode(key);; //需要插入链表的结点
//判断为非空结点和插入位置
while(p!=*h && p->key < key){
p=p->next;
}
//插入元素
q->pre=p->pre;
p->pre->next=q;
q->next=p;
p->pre=q;
}
int DelElem(PNode *h, int key){
PNode p=(*h)->next;
while(p!=*h && p->key!=key){
p=p->next;
}
//未找到该节点
if(p==*h) return -1;
else{
p->pre->next=p->next;
p->next->pre=p->pre;
free(p);
return 1;
}
}
void PrintLink(PNode h){
for(PNode p=h->next;p!=h;p=p->next)
printf("%d ", p->key);
printf("\n");
}
int main(){
int i,tmp;
PNode head;
IniLink(&head); //初始化头结点
srand((unsigned)time(NULL));
for(i=0;i<N;i++){
tmp=rand()%N_RAND;
printf("%d ",tmp);
InsertElem(&head,tmp);//插入结点
}
printf("\n");
PrintLink(head);
int delElem;
while(head->next != head){
printf("请输入要删除的结点:");
scanf("%d",&delElem);
if(DelElem(&head,delElem)<0)
printf("没有%d这个结点\n",delElem);
PrintLink(head);
}
printf("链表为空,游戏结束:-)\n");
system("pause");
return 0;
}