一道链表相关的笔试题
2012-04-07 00:33
232 查看
从网上搜到的笔经:
题目大致如下:
写代码。把一个单链表,按照指定位置逆序。并在code中体现基本错误异常处理之类。
不能再多malloc内存了,可以用temp pointers。还有一个不允许的什么条件没看懂,无 碍大雅吧。
eg。n1->n2->n3->n4->n5->null phead = n1;pstart = n3;返回这个n3->n2->n1->n5-> n4->null
eg。n1->n2->n3->n4->n5->null phead = n1;pstart = n5;返回这个n5->n4->n3->n2-> n1->null
eg。n1->n2->n3->n4->n5->null phead = n1;pstart = n1;返回这个n1->n5->n4->n3-> n2->null
实现代码如下:
题目大致如下:
写代码。把一个单链表,按照指定位置逆序。并在code中体现基本错误异常处理之类。
不能再多malloc内存了,可以用temp pointers。还有一个不允许的什么条件没看懂,无 碍大雅吧。
eg。n1->n2->n3->n4->n5->null phead = n1;pstart = n3;返回这个n3->n2->n1->n5-> n4->null
eg。n1->n2->n3->n4->n5->null phead = n1;pstart = n5;返回这个n5->n4->n3->n2-> n1->null
eg。n1->n2->n3->n4->n5->null phead = n1;pstart = n1;返回这个n1->n5->n4->n3-> n2->null
实现代码如下:
#include <iostream> using namespace std; typedef struct _node { int key; _node * next; _node(int k) {key = k;} ~_node(); } node; void reverse(node* &phead, node* &pstart) {\ if (phead == NULL ) return; if (pstart == NULL) return; node *p = phead; node *pnext = p->next; node *prev = NULL; while (prev!=pstart && pnext!=NULL) { pnext = p->next; p->next = prev; prev = p; p = pnext; } prev = NULL; while(pnext!=NULL) { pnext = p->next; p->next = prev; prev = p; p = pnext; } phead->next = prev; phead = pstart; } void main() { node *p = new node(1); node *phead = p; for (int i = 2; i < 6; i++) { p->next = new node(i); p = p->next; } p->next = NULL; node *pstart = phead; reverse(phead, pstart); p = phead; while (p!=NULL) { cout << p->key << " "; p = p->next; } cout << endl; }
相关文章推荐
- 笔试面试,单链表相关(3)遍历一次找中间结点、倒数第K个结点
- 一道华为笔试题 ,内存相关
- <笔试><面试>C/C++单链表相关(4)判断两链表是否相交,求交点(链表不带环/可能带环)
- 每天一道算法题--单链表的相关操作
- 一道网易笔试题目-几何相关
- 笔试面试,单链表相关(3)遍历一次找中间结点、倒数第K个结点
- 面试笔试系列之二 链表相关
- 链表相关笔试面试题
- 笔试面试单链表相关(2)在任意位置前插入结点、逆置链表
- <笔试><面试>单链表相关(1)从尾到头打印链表、删除一个无头链表的非尾结点
- 链表相关笔试题(一)
- 链表相关笔试题(二)
- <笔试><面试>C/C++单链表相关(4)判断两链表是否相交,求交点(链表不带环/可能带环)
- 链表相关笔试题
- 单链表相关面试笔试题
- 【笔试面试】链表相关操作
- <笔试><面试>单链表相关(1)从尾到头打印链表、删除一个无头链表的非尾结点
- 单链表相关笔试题:单链表逆转,约瑟夫环等
- 笔试面试单链表相关(2)在任意位置前插入结点、逆置链表
- 笔试算法学习--链表相关