您的位置:首页 > 职场人生

[面试]双向循环链表求深度

2015-10-12 19:53 253 查看
今天面中兴,题目是求双向循环链表的深度,发现还是不太会,回来敲了一遍。思路是循环便利直到尾节点,尾节点的标志是,其下一个节点是头结点。

#include <stdlib.h>
#include <stdio.h>

//typedef enum bool
//{
// FALSE = 0,
// TRUE = 1
//}BOOL;

typedef struct biListNode
{
int ele;
biListNode* next;
biListNode* prev;
}BL_NODE;

bool insert(BL_NODE* head, int ele)
{
if(head == NULL || head->next == NULL)
return false;

BL_NODE* newNode = (BL_NODE*)malloc(sizeof(BL_NODE));

newNode -> ele = ele;

if(head -> next == head)
{
head->next = newNode;
head->prev = newNode;
newNode ->next = head;
newNode->prev = head;
return true;
}

newNode -> prev = head->prev;
newNode -> next = head;

head -> prev -> next = newNode;
head -> prev = newNode;
}

int getLength(BL_NODE* head)
{
if(head == NULL || head -> next == NULL)
return 0;

if(head -> next == head)
return 1;

int ret = 1;

BL_NODE* tmp = head;
while(tmp -> next != head)
{
tmp = tmp -> next;
ret ++;
}

return ret;
}

int main(void)
{
BL_NODE* list = (BL_NODE*)malloc(sizeof(BL_NODE));
list-> ele = 0;
list-> next = list;
list-> prev = list;

insert(list, 1);
insert(list, 2);
insert(list, 4);

int len = 0;
len = getLength(list);

printf("the length of the list is %d\n", len);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试 链表 c语言