本节代码来源于<<数据结构-使用C语言>>朱战立 编著
为了熟悉链表和堆栈,学习了这本书。为了更加熟悉原理,敲下书上代码熟悉熟悉。
#include <iostream>
typedef struct Node{
int data;
struct Node* next;
struct Node* prior;
}SLNode;
/*初始化一个双向链表*/
void ListInitiate(SLNode** head)
{
if((*head = (SLNode*)malloc(sizeof(SLNode)))==NULL)exit(0);
(*head)->next = *head;
(*head)->prior = *head;
}
/**链表长度/.
int ListLength(SLNode* head)
{
SLNode* p = head;
int size = 0;
while(p->next != head){
p = p->next;
size++;
}
return size;
}
/*插入数据*/
int ListInsert(SLNode* head, int i, int x)
{
SLNode* p, *q;
int j;
p = head->next;
j = 0;
while(p != head && j < i){
p = p->next;
j++;
}
if(j != i){
printf("插入位置参数错!\n");
return 0;
}
if((q = (SLNode*)malloc(sizeof(SLNode))) == NULL)exit(0);
q->data = x;
q->prior = p->prior;
p->prior->next = q;
q->next = p;
p->prior = q;
return 1;
}
/*删除节点*/
int ListDelele(SLNode* head, int i, int* x)
{
SLNode* p;
int j;
p = head->next;
j = -1;
while(p->next != head && j < i){
p = p->next;
j++;
}
if(j != i){
printf("删除位置参数错误\n");
return 0;
}
p->prior->next = p->next;
p->next->prior = p->prior;
*x = p->data;
free(p);
return 1;
}
/*获取数据*/
int ListGet(SLNode* head, int i, int* x)
{
SLNode* p;
int j;
p = head;
j = -1;
while(p->next != head && j < i){
p = p->next;
j++;
}
if(j != i){
printf("取元素位置参数错误!\n");
return 0;
}
*x = p->data;
return 1;
}
/*销毁链表*/
void Destroy(SLNode** head)
{
SLNode* p, *p1;
int i,n = ListLength(*head);
p = *head;
for(i = 0; i <= n; i++){
p1 = p;
p = p->next;
free(p1);
}
*head = NULL;
}
int main()
{
SLNode* listNode;
ListInitiate(&listNode);
int ret = ListInsert(listNode, 0, 1);
int lens = ListLength(listNode);
printf(" lens = %d\n", lens);
Destroy(&listNode);
return 0;
}