Leetcode 24 :Swap Nodes in Pairs
来源:互联网 发布:面包板是做单片机的吗 编辑:程序博客网 时间:2024/06/09 22:40
题目大意:给定一个链表,交换其中相邻的2个元素
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.
Subscribe to see which companies asked this question
/** * 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) return NULL; if(head != NULL && head->next == NULL) return head; ListNode* headF = new ListNode(0); headF->next = head; ListNode* headO = headF; while(headO->next != NULL && headO->next->next != NULL) { // ListNode* tmpN1 = headO->next->next->next; ListNode* tmpN = headO->next; headO->next = headO->next->next; headO->next->next = tmpN; headO->next->next->next = tmpN1; headO = headO->next->next; } ListNode*Re = headF->next; delete headF; return Re; }};
class Solution {public: ListNode* swapPairs(ListNode* head) { bool first = true; ListNode *pFirst = head, *pSecond = NULL, *pTail = NULL, *ret = head; while (pFirst && pFirst -> next) { // 判断是否存在两个后继元素 pSecond = pFirst -> next; // 获取pSecond if (first) ret = pSecond; // 处理链表头 if (!first) pTail -> next = pSecond; // 处理链表中段 pFirst -> next = pSecond -> next; pSecond -> next = pFirst; // 交换元素 pTail = pFirst; // 更新链表末尾 pFirst = pFirst -> next; // 进行到下一个元素 first = false; } return ret; }};
0 0
- LeetCode(24)Swap Nodes in Pairs
- [LeetCode 24] Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs
- LeetCode | #24 Swap Nodes in Pairs
- [Leetcode 24 链表]Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- 【leetcode】【单链表】【24】Swap Nodes in Pairs
- Leetcode 24 Swap Nodes in Pairs
- Swap Nodes in Pairs - LeetCode 24
- LeetCode 24 - Swap Nodes in Pairs
- leetcode 24 -- Swap Nodes in Pairs
- LeetCode 24:Swap Nodes in Pairs
- leetcode-24Swap Nodes in Pairs
- leetcode 24: Swap Nodes in Pairs
- Leetcode#24 Swap Nodes in Pairs
- LeetCode 24: Swap Nodes in Pairs
- LeetCode(24) Swap Nodes in Pairs
- [Leetcode 24, Medium] Swap Nodes in Pairs
- 类别(Category)的作用(一)---将实现分散到不同文件
- Android 调用系统内置分享
- Scala数组操作
- ssh
- python字符串比较
- Leetcode 24 :Swap Nodes in Pairs
- 小米架构师:亿级大数据实时分析与工具选型(附PPT)
- linux下自动化部署apache + php环境
- 20160712梅西法&科利法.md
- 果然咸鱼还是一如既往的咸鱼
- UVA11292 HDU1902 POJ3646 Dragon of Loowater
- 开关频率
- 29. Spring boot 文件上传(多文件上传)【从零开始学Spring Boot】
- dp做题的基本思路和优化思想