LeetCode-24-Swap Nodes in Pairs(链表)-Medium
来源:互联网 发布:网络每4分钟断一次 编辑:程序博客网 时间:2024/05/21 06:19
题意理解:
交换链表中相邻的两个元素,如原链表为a->b->c->d,修改为b->a->d->c;
题目分析:
1. 不能重新分配多余内存,即只修改指针指向,不增加新的节点内容;
2. 标示要处理的两个相邻元素位置p1,p2,以及p1之前的位置pPre和p2之后的位置pNext;
3. 根据题目要求交换对应位置指针的指向内容;
解题代码:
/** * 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* ans=head; int size=0; ListNode* pCur=head; while(pCur!=NULL){ size++; pCur=pCur->next; } pCur=head; if(size<=1){ return ans; } ListNode* pPre=new ListNode(0); ans=pPre; ListNode* p1; ListNode* p2; ListNode* pNext; for(int i=0; i<size; i+=2){ if(i==0){ pNext=head->next->next; p1=head; p2=head->next; } pPre->next=p2; p2->next=p1; p1->next=pNext; if(i+2>=size-1){ break; } pPre=p1; p1=pPre->next; p2=p1->next; pNext=p2->next; } return ans->next; }};
0 0
- [Leetcode 24, Medium] Swap Nodes in Pairs
- LeetCode-24-Swap Nodes in Pairs(链表)-Medium
- Leetcode OJ 24 Swap Nodes in Pairs [Medium]
- [Leetcode 24 链表]Swap Nodes in Pairs
- leetcode #24 swap nodes in pairs 链表
- [LeetCode] 024. Swap Nodes in Pairs (Medium) (C++/Python)
- LeetCode刷题——Swap Nodes in Pairs(Medium)
- [Leetcode 24, Medium] Swap Nodes in Pair
- leetcode Swap Nodes in Pairs 链表
- [LeetCode][链表]Swap Nodes in Pairs
- [leetcode] 【链表】24. Swap Nodes in Pairs
- leetcode---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
- JavaScript分类显示随机颜色【红绿蓝青黄紫、黑白、全彩】
- Linux下yum命令详解
- react-native css属性
- 涉及到指针、数组、堆栈、以及printf
- jar包中导入新的类
- LeetCode-24-Swap Nodes in Pairs(链表)-Medium
- Studio快捷键
- Myeclipse 解决 Myeclipse build workspace慢,validation javascript,jsp慢的问题
- Generate Parentheses
- setjmp用法
- bzoj3140: [Hnoi2013]消毒
- Java深入(面试常见题)
- Bootstrap list click 事件
- createJs游戏引擎