2013.12.7 01:54
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.
Solution:
This kind of problem is designed just to make some trouble for you, and the interviewer must be very glad watching you getting into a bloody mess with the code. So let's first write down the process in language description:
1. use two pointers p2 pointing to the first/second node in each pair.
2. change the $next pointers of p1 and p2
3. swap p2, make sure p2.
4. record current par, which will be used in the next pair.
5. move both p2 forward by two steps, don't forget to check for nullptr.
6. {do the swapping for the next pair}, and point p1
Time complexiy is O(n), space complexity is O(1). The real problem is whether you can write the code nice and clean. Try to be careful and patient.
Accepted code:
// This problem is tricky, 3WA /** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ListNode *p1 = nullptr, *p2 = nullptr; if(head == nullptr){ return head; } p1 = head; p2 = head->next; if(p2 == nullptr){ return p1; } bool first_swap = true; ListNode *tmp, *par; ListNode *root; par = new ListNode(0); root = par; par->next = p1; while(true){ p1->next = p2->next; p2->next = p1; tmp = p1; p1 = p2; p2 = tmp; par->next = p1; par = p2; if(first_swap){ head = p1; first_swap = false; } p1 = p1->next; p2 = p1->next; if(p2 == nullptr){ break; } p1 = p1->next; p2 = p1->next; if(p2 == nullptr){ break; } } delete root; root = nullptr; return head; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)