[面试]双向循环链表求深度
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;
}
#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/C++]反转链表
- 只有程序员看的懂的面试圣经|如何拿下编程面试
- 下一次技术面试时要问的 3 个重要问题
- C#实现基于链表的内存记事本实例
- Lua和C语言的交互详解
- PHP程序员面试 切忌急功近利(更需要注重以后的发展)
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言中fchdir()函数和rewinddir()函数的使用详解
- C语言内存对齐实例详解
- 使用C语言判断英文字符大小写的方法
- c语言实现的带通配符匹配算法
- C语言实现顺序表基本操作汇总
- C语言中计算正弦的相关函数总结
- 使用C语言详解霍夫曼树数据结构
- 探讨C语言的那些小秘密之断言
- C语言实现BMP转换JPG的方法
- 深入探讨C语言中局部变量与全局变量在内存中的存放位置