24. Swap Nodes in Pairs
来源:互联网 发布:淘宝banner小图标 编辑:程序博客网 时间:2024/06/10 12:02
问题描述:
问题分析:
1)这道题属于链表操作的题目,思路比较清晰,每次跳两个节点
2)这道题中用了一个辅助指针作为表头,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧
图解分析:
①初始化:
②first.next=second.next
③current.next=second
④current.next.next=first
⑤current = current.next.next
JAVA代码展示:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution { public ListNode swapPairs(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode current = dummy; while (current.next != null && current.next.next != null) { ListNode first = current.next; ListNode second = current.next.next; first.next = second.next; current.next = second; current.next.next = first; current = current.next.next; } return dummy.next; }}
运行图片展示:
C语言描述:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */
struct ListNode* swapPairs(struct ListNode* head) { if(head ==NULL) return NULL; struct ListNode *dummy = (struct ListNode*)malloc(sizeof(struct ListNode)); dummy->next = head; struct ListNode *current = dummy; while(current->next!=NULL && current->next->next!=NULL){ struct ListNode *ptr1 = head; struct ListNode *ptr2 = head->next; ptr1->next = ptr2->next; current->next =ptr2; current->next->next = ptr1; current=current->next->next; } return current->next;}
运行图片展示:
阅读全文
0 0
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 缓存
- 16位汇编x86_寻址方式
- 2、数据结构笔记之二线性表
- ubuntu安装eclipse web和jeez插件处想 Cannot satisfy dependency问题
- memached简介
- 24. Swap Nodes in Pairs
- android 四大组件之Activity
- 笔记
- 双线性插值算法进行图像缩放及性能效果优化
- ssh三层框架——上传文件(大小格式筛选+json返回相对地址)
- CrodeForces 851B--#432 Div2 B
- spark
- react native 的底部导航栏以及跳转页面带参数
- flush , shutdownOutput, close有什么区别