(程序员面试题)单链表的反转
来源:互联网 发布:软件需求工程课题 编辑:程序博客网 时间:2024/05/02 04:34
只用一个额外的节点实现单链表的反转
testcase如下:
#include <stdio.h>#include <stdlib.h>typedef struct num { int data; struct num *next;} *num_ptr;void print_num(num_ptr head) { num_ptr tmp = head; while (tmp->next) { printf("%d\n", tmp->next->data); tmp = tmp->next; } printf("\n"); } num_ptr reverse_link(num_ptr head) { num_ptr priv = head->next; num_ptr cur = head->next->next; num_ptr tmp = (num_ptr)malloc(sizeof(struct num)); tmp->next = cur->next; priv->next = NULL; while (cur->next) { // start reverse cur->next = priv; // priv change to next priv = cur; // cur change to next, this is why need tmp node cur = tmp->next; // tmp still save cur next tmp->next = cur->next; } // change last node next null to priv cur->next = priv; head->next = cur; return head;}int main(){ num_ptr head, one, two, three, four; head = (num_ptr)malloc(sizeof(struct num)); one = (num_ptr)malloc(sizeof(struct num)); two = (num_ptr)malloc(sizeof(struct num)); three = (num_ptr)malloc(sizeof(struct num)); four = (num_ptr)malloc(sizeof(struct num)); one->data = 1; two->data = 2; three->data = 3; four->data = 4; head->next = one; one->next = two; two->next = three; three->next = four; four->next = NULL; print_num(head); num_ptr new_head = reverse_link(head); print_num(new_head); return 0;}
这个问题的关键就在于那一个额外的节点,因为当链表做完反转之后就无法指向链表的下一个节点了,这个时候用额外的节点去记住反转的节点的下一个节点,这样子就可以继续进行下一轮反转了
0 0
- (程序员面试题)单链表的反转
- 单链表的反转(数据结构 面试题)
- 面试题-单链表反转
- 【面试题】-单链表反转
- 单链表反转面试题
- 程序员面试题精选(19):反转链表
- (程序员面试题)字符串处理之字符反转
- (程序员面试题)字符串处理之单词反转
- 嵌入式软件工程师面试题--字符串的反转
- java面试题:字符串的反转
- 剑指offer算法题之单链表的反转--面试题16:反转链表
- [程序员面试题精选100题]19.反转链表
- 剑指offer 面试题16 反转单链表
- 链式存储面试题-单链表反转
- 多种单链表反转面试题总结
- bat面试题 python 单链表反转排序
- 面试题:反转字符串
- 【面试题】-反转句子
- Giraph源码分析(二)——启动Master/Worker服务
- 在Android系统中开发DLNA
- 2012年末工作中遇到的问题总结及感悟
- BUAA Training 2014.03.29 Fukuoka-2011
- html5学习笔记
- (程序员面试题)单链表的反转
- iOS&Java常用加密(一)
- GUID基础
- 【DFS+BFS】hdu 1983 Kaitou Kid - The Phantom Thief (2)(迷宫)
- 【面向对象程序设计常见面试题】派生中构造函数的几点说明(xx)
- Echarts使用心得总结(二)
- eclipse Juno Indigo Helios Galileo这几种版本的意思
- CodeForces 339A Helpful Maths
- 时间复杂度计算