leetcode 题解 || Swap Nodes in Pairs 问题
2016-03-29 16:47
1011 查看
problem:
在单链表中。每两个结点交换一下位置。单个的不交换
thinking:
(1)这道题在不新建结点的情况下。指向关系复杂。慢慢分析
(2)head是头指针,指向第一个有效结点!
!
!
code:
Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
在单链表中。每两个结点交换一下位置。单个的不交换
thinking:
(1)这道题在不新建结点的情况下。指向关系复杂。慢慢分析
(2)head是头指针,指向第一个有效结点!
!
!
code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swapPairs(ListNode *head) { ListNode *index = head; ListNode *pre = NULL; ListNode *tmp = NULL; ListNode *modify = head;; int i=0; if(head==NULL||head->next==NULL) return head; while((index!=NULL)&&(index->next!=NULL)) { i++; pre=index; if(i==1) { head=pre->next; index = index->next; tmp = index->next; pre->next = tmp; index->next = pre; index=tmp; modify=pre; } else { index = index->next; tmp = index->next; modify->next=pre->next; pre->next = tmp; index->next = pre; index=tmp; modify=pre; } } return head; } };
相关文章推荐
- node.js 入门实例【转】
- Hadoop获得集群NameNode和DataNode状态
- node.js学习笔记(4)--使用Express完成简单的登陆
- node.js的REPL运行环境中的基本命令汇总
- Node.js初体验
- Node.js入门学习(概述)
- 新手如何快速入门node.js
- hadoop Name node is in safe mode
- Namenode HA原理详解(脑裂)
- Remove Node in Binary Search Tree
- JavaScritpt的DOM初探之Node(一)
- 找到个学node的好地方,极客学院
- LeetCode笔记:237. Delete Node in a Linked List
- node.js学习笔记之浅谈观察者模式
- node.js版本升级
- Node.js:实现知乎(www.zhihu.com)模拟登陆,获取用户关注主题
- nodejs save遇到的一个坑
- node.js中express-session配置项详解
- 格式化Namenode提示Call From n1/192.168.253.130 to s1:8485 failed on connection exception: java.net.Connec
- node 学习的一些资料收集