链表的笔试题
2016-01-04 19:58
344 查看
单向链表节点定义:
typedef struct node { int data; struct node *next; }Node,*pNode;双向链表节点定义:
typedef struct node { int data; struct node *next; struct node *pre; }Node,*pNode;
链表逆序
非递归方法:pNode RevertList(pNode head) { if ((head == NULL) || (head->next == NULL)) return head; pNode p1 = head; pNode p2 = p1->next; pNode p3 = p2->next; p1->next = NULL; while(p3 != NULL) { p2->next = p1; p1 = p2; p2 = p3; p3 = p3->next; } p2->next = p1; head = p2; return head; }递归方法:
pNode RevertList(pNode head) { pNode p1 = NULL; if ( (head == NULL) || (head->next == NULL)) return head; p1 = RevertList(head->next); head->next->next = head; head->next = NULL; return p1; }
将2个有序的链表合并成一个有序链表
非递归方法:pNode MergeList(pNode head1, pNode head2) { if (head1 == NULL) return head2; if (head2 == NULL) return head1; pNode p1 = NULL; pNode p2 = NULL; pNode head = NULL; if (head1->data < head2->data) { head = head1; p1 = head1->next; p2 = head2; } else { head = head2; p1 = head1; p2 = head2->next; } pNode curNode = head; while((p1 != NULL) && (p2 != NULL)) { if (p1->data < p2->data) { curNode->next = p1; curNode = p1; p1 = p1->next; } else { curNode->next = p2; curNode = p2; p2 = p2->next; } } if (p1 == NULL) curNode->next = p2; else curNode->next = p1; return head; }递归方法:
pNode MergeList(pNode head1, pNode head2) { if (head1 == NULL) return head2; if (head2 == NULL) return head1; pNode head = NULL; if (head1->data < head2->data) { head = head1; head->next = MergeList(head1->next, head2); } else { head = head2; head->next = MergeList(head1, head2->next); } return head; }
判断一个单链表是有环的
bool CheckLoop(const pNode head) { if (head == NULL) return false; pNode low = head; pNode fast = head->next; while((fast != NULL) && (fast->next != NULL)) { if (low == fast) return true; low = low->next; fast = fast->next->next; } return false; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- [C/C++]反转链表
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- C#实现基于链表的内存记事本实例
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例