LeetCode 24. Swap Nodes in Pairs
2016-07-22 13:27
471 查看
24. Swap Nodes in Pairs
My Submissions QuestionEditorial Solution
Total Accepted: 91202 Total Submissions: 260548 Difficulty: Easy
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.
My Submissions QuestionEditorial Solution
Total Accepted: 91202 Total Submissions: 260548 Difficulty: Easy
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.
/** * 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) { if(head == NULL || head->next == NULL) { return head; } ListNode *p, *q, *h, *t; p = head; q = head->next; h = q; while(p != NULL && q != NULL) { p->next = q->next; q->next = p; t = p; if(p->next != NULL) { p = p->next; } else { return h; } if(p->next != NULL) { q = p->next; t->next = q; } else { return h; } } } };
相关文章推荐
- nodejs安装express遇到的坑
- Nodejs使用mailer发送邮件(未测试)
- Keep a node.js server up with Forever
- 建议直接从inode 获取设备号
- nodejs与Sublime相结合
- Node.js:全局对象
- Node.js 上传文件formidable时使用fs.renameSync报错
- 在腾讯云(windows)上搭建node.js服务器
- inode获取设备号
- webstorm中配置nodejs环境及npm
- Node.js:回调函数
- Node.js:模块
- Node.js:包
- pat 1115 Counting Nodes in a BST (30)
- nodejs 记入
- [leetcode] Swap Nodes in Pairs
- LeetCode 19. Remove Nth Node From End of List
- 低版本MonoDevelop转移到高版本MonoDevelop的Editor问题
- node.js 实现一个简单的登录拦截器
- node.js AES/ECB/PKCS5Padding 与其他语言的加密解密通用