【leetcode】Swap Nodes in Pairs
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.
一A的水题,哦啦啦啦啦~
就注意一点:不能光顾着该当前的两个链表节点的指针,还要用last_pair存放上一组最后一个节点的指针,以修改这个节点的next指针指向当前组新的第一个指针。如果没有上一组时候要特殊处理head指针。有点饶,举个例子,题目给的例子里面,当交换1,2的时候注意head指针要指向2而不是1;交换完1,2得到如下链表2->1->3->4,当交换3,4的时候注意要修改1的next指针指向4。
代码如下:
1 #include <iostream> 2 using namespace std; 3 struct ListNode { 4 int val; 5 ListNode *next; 6 ListNode(int x) : val(x), next(NULL) {} 7 }; 8 9 class Solution { 10 public: 11 ListNode *swapPairs(ListNode *head) { 12 ListNode* current = head; 13 ListNode* last_pair = head; 14 while(current != NULL){ 15 ListNode* temp = current->next; 16 if(temp != NULL){ 17 if(last_pair == head) 18 head = temp; 19 else 20 last_pair->next = temp; 21 last_pair = current; 22 current->next = temp->next; 23 temp->next = current; 24 } 25 26 current = current->next; 27 } 28 return head; 29 } 30 }; 31 32 int main(){ 33 Solution s; 34 ListNode* head = new ListNode(1); 35 ListNode* node1= new ListNode(2); 36 head->next = node1; 37 38 ListNode* node2= new ListNode(3); 39 node1->next = node2; 40 41 ListNode* node3= new ListNode(4); 42 node2->next = node3; 43 44 ListNode* r = s.swapPairs(head); 45 while(r != NULL){ 46 cout <<r->val<<endl; 47 r = r->next; 48 } 49 }
JAVA版本:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode swapPairs(ListNode head) { 14 if(head == null) 15 return head; 16 17 ListNode newHead = null; 18 ListNode one = head; 19 ListNode two = head.next; 20 ListNode before = null; 21 22 while(one != null && two != null){ 23 ListNode three = two.next; 24 two.next = one; 25 one.next = three; 26 27 if(newHead == null) 28 { 29 newHead = two; 30 before = one; 31 }else { 32 before.next = two; 33 before = one; 34 } 35 one = three; 36 if(one != null) 37 two = one.next; 38 } 39 if(one != null && before != null) 40 before.next = one; 41 return newHead==null?head:newHead; 42 } 43 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了