博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
链表逆序问题
阅读量:4071 次
发布时间:2019-05-25

本文共 1302 字,大约阅读时间需要 4 分钟。

传送门:   购买视频请输入优惠码  AdVHxHT 可优惠10元

题目描述:

有一个单链表,请设计一个算法,使得每K个节点之间逆序,如果最后不够K个节点一组,则不调整最后几个节点。例如链表1->2->3->4->5->6->7->8->null,K=3这个例子。调整后为,3->2->1->6->5->4->7->8->null。因为K==3,所以每三个节点之间逆序,但其中的7,8不调整,因为只有两个节点不够一组。

给定一个单链表的头指针head,同时给定K值,返回逆序后的链表的头指针。

AC 代码

class KInverse {public:    ListNode* inverse(ListNode* head, int k) {        stack
s; ListNode * newHead = NULL,*last=NULL; while (head) { ListNode *tmp = head->next; head->next = NULL; s.push(head); head = tmp; if(s.size()==k){ while (!s.empty()) { if(newHead==NULL){ newHead = s.top(); last = s.top(); }else{ last->next = s.top(); last = s.top(); } s.pop(); } } } ListNode * remain=NULL; while (!s.empty()) { if(remain==NULL){ remain = s.top(); }else{ (s.top())->next = remain; remain = s.top(); } s.pop(); } if(newHead==NULL) return remain; else{ last->next = remain; return newHead; } }};

转载地址:http://ehhji.baihongyu.com/

你可能感兴趣的文章
web.py操作mysql的数据
查看>>
python类的详析
查看>>
web.py的两种更新Mysql数据的方法
查看>>
前端网址总结
查看>>
前端知识总结一
查看>>
Python 字符串的操作
查看>>
python安装依赖modules pysnmp pyasn1.type pexpect configparser
查看>>
Python操作Mongodb插入数据的两种方法:insert_one()与insert_many()
查看>>
Python函数式编程——匿名函数lambda
查看>>
Python的getattr(),setattr(),delattr(),hasattr()
查看>>
js中的constructor与prototype
查看>>
Ajax中的get和post请求比较
查看>>
'VBoxManage' is not recognized as an internal or external command, operable program or batch file.
查看>>
Linux VNC server的安装及简单配置使用
查看>>
解决RHEL6 vncserver 启动 could not open default font 'fixed'错误.
查看>>
Linux 下路由的设置
查看>>
CentOS/Linux 网卡设置 IP地址配置
查看>>
Python实现ping指定IP
查看>>
linux下ping命令使用详解
查看>>
html引入jquery库
查看>>