当前位置:网站首页>1721. exchange nodes in the linked list
1721. exchange nodes in the linked list
2022-06-11 08:55:00 【Drag is me】
leetcode Force button to brush questions and punch in
subject :1721. Exchange the nodes in the linked list
describe : Give you the head node of the list head And an integer k .
In exchange for Positive number of linked list k Nodes and penultimate k After the value of a node , Return the head node of the linked list ( Linked list from 1 Start index ).
Their thinking
1、 Use an array to store linked list nodes , Locate two target nodes with subscripts , Then exchange ;
2、 Double pointer is OK , See the code 2.
Source code 1##
class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
vector<ListNode *>v;
ListNode *p = new ListNode(-1);
ListNode *pp = p;
int n = 0;
while (head) {
v.emplace_back(head);
head = head->next;
}
n = v.size();
int val = v[k - 1]->val;
v[k - 1]->val = v[n - k]->val;
v[n - k]->val = val;
for (int i = 0; i < n; ++i) {
p->next = v[i];
p = p->next;
}
p->next = nullptr;
return pp->next;
}
};
Source code 2##
class Solution {
public:
ListNode* swapNodes(ListNode* head, int k) {
ListNode *fast = head;
for (int i = 1; i < k; ++i) {
fast = fast->next;
}
ListNode *temp = fast;
ListNode *slow = head;
while (fast->next != nullptr) {
fast = fast->next;
slow = slow->next;
}
swap(slow->val, temp->val);
return head;
}
};
边栏推荐
- Supplement 2: circle returning to origin
- Is it appropriate to apply silicone paint to American Standard UL 790 class a?
- E. Zoom in and zoom out of X (operator overloading)
- Codetop - sort odd ascending even descending linked list
- MySQL核心点笔记
- 利用docker-compose搭建redis5集群
- Standardized compilation knowledge
- MATLAB R2022a 安装教程
- Matlab learning 8- linear and nonlinear sharpening filtering and nonlinear smoothing filtering of image processing
- LiveData 与 StateFlow,我该用哪个?
猜你喜欢

How to apply for BS 476-7 sample for display? Is it the same as the display

leetcode - 460. LFU 缓存

【C语言-函数栈帧】从反汇编的角度,剖析函数调用全流程

Matlab学习7-图像处理之线性平滑滤波

Not eligible for getting processed by all beanpostprocessors

剑指 Offer 21. 调整数组顺序使奇数位于偶数前面

窗帘做EN 1101易燃性测试过程是怎么样的?

Sword finger offer 62 The last remaining number in the circle

Codetop - sort odd ascending even descending linked list

leetcode - 230. The k-th smallest element in a binary search tree
随机推荐
EN 45545-2:2020 T11 smoke toxicity test
MySQL核心点笔记
完整的ES6面试题
PHP uploading large files for more than 40 seconds server 500
九九乘法表
leveldb简单使用样例
PHP solves Chinese display garbled code
What is the process of en 1101 flammability test for curtains?
显示器要申请BS 476-7 怎么送样?跟显示屏一样吗
EN45545-2 R26垂直燃烧测试介绍
Standardized compilation knowledge
Complete ES6 questions
光伏板怎么申请ASTM E108阻燃测试?
CodeTop - 排序奇升偶降链表
Why is the string class final decorated
2130. 链表最大孪生和
Screening frog log file analyzer Chinese version installation tutorial
String类为何final修饰
剑指 Offer 51. 数组中的逆序对
c的printf相关