【转载请注明】https://www.cnblogs.com/igoslly/p/9351564.html

具体的图示可查看 链接


代码一

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if(head==NULL || head->next ==NULL) return;
// two pointers split the list
// 快慢指针,快指针到尾时,慢指针在前list尾部
// example: 1->2->3->4->5 fast=5,slow=3, 1->2->3 & 4->5
// example: 1->2->3->4 fast=3,slow=2, 1->2 & 3->4
ListNode *slow = head, *fast = head;
while(fast->next !=NULL && fast->next->next !=NULL){
slow = slow ->next;
fast = fast->next->next;
}
ListNode *head1 = head;
// reverse the second list(with large numbers)
// 翻转第二个链表
ListNode *head2 = reverseList(slow->next);
slow->next = NULL;
while(head2!=NULL){ // list1 size >= list2 size
ListNode *next1 = head1->next;
ListNode *next2 = head2->next;
head1->next = head2;
head2->next = next1;
head1 = next1;
head2 = next2;
}
if(head1!=NULL){
head1->next = NULL;
}
}
// reverse list
ListNode *reverseList(ListNode *head){
if(head==NULL || head->next ==NULL) return head;
ListNode * new_head = NULL;
while(head!=NULL){
ListNode *pNext = head->next;
head->next = new_head;
new_head = head;
head = pNext;
}
return new_head;
}
};

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
stack<ListNode* > nodestack;
int length=;
// 计算链表长度,结点压入stack
ListNode *temp = head;
while(temp){
length++;
nodestack.push(temp);
temp = temp->next;
}
// 栈弹出,连接链表
temp = head;
int cnt = length/;
while(cnt){
ListNode *head2 = nodestack.top();
nodestack.pop();
ListNode *headNext = temp->next;
temp->next =head2;
head2->next = headNext;
temp = headNext;
cnt--;
}
// 总数为odd,temp指向末尾元素
// 总数为even,temp会和前元素重复,此处删除
if(length%){
temp->next = NULL;
}else{
temp = NULL;
}
}
};

最新文章

  1. T-SQL实用查询之分析数据库表的大小
  2. NSRunLoop详解
  3. SWT, JFace必须的jar包和有可能会用到的jar
  4. 如何改变Activity在当前任务堆栈中的顺序,Intent参数大全
  5. 单步调试 step into/step out/step over 区别
  6. js之Function原型
  7. 在CentOS6上使用YUM安装php5.5.x
  8. Python urllib和urllib2模块学习(三)
  9. 断言Assert的使用
  10. Android Studio调试功能使用总结---转
  11. 201521123053《Java程序设计》第1周学习总结
  12. 控制结构(8) 线性化(linearization)
  13. HiWord()
  14. Android实训案例(二)——Android下的CMD命令之关机重启以及重启recovery
  15. Uniform Generator
  16. Adams输出宏代码
  17. 360极速浏览器极速模式通过hosts文件切换兼容模式bat脚本
  18. sqlserver 发送http请求
  19. Redis、RabbitMQ、Memcached
  20. DataBinding(二):DataBinding的基本用法

热门文章

  1. 测试出来了第一版代码--可以得到用户token啦
  2. Ubuntu 16.04安装GIMP替代PS
  3. Spring Tool Suite(STS)启动时出现错误:Java was started but returned exit code=13问题解决
  4. MySQL: Create Master - Slave Servers
  5. 【CV论文阅读】:Rich feature hierarchies for accurate object detection and semantic segmentation
  6. oracle em 5500访问问题
  7. Ndk开发笔记
  8. HDU 1421 搬寝室 (线性dp 贪心预处理)
  9. 大话设计模式宏观总结——创建型&amp;amp;结构型&amp;amp;行为型
  10. 【线程安全】—— 单例类双重检查加锁(double-checked locking)