LeetCode实战:两两交换链表中的节点
2019-04-18 本文已影响0人
老马的程序人生
题目英文
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
题目中文
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
算法实现
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution
{
public ListNode SwapPairs(ListNode head)
{
if (head == null || head.next == null)
return head;
head = Swap(head);
ListNode temp = head.next;
while (temp != null && temp.next != null)
{
temp.next = Swap(temp.next);
if (temp.next != null)
{
temp = temp.next.next;
}
}
return head;
}
public ListNode Swap(ListNode node)
{
if (node == null || node.next == null)
return node;
ListNode t = node.next;
node.next = t.next;
t.next = node;
return t;
}
}
实验结果
![](https://img.haomeiwen.com/i3648525/0f6750ff01df7e45.png)
相关图文:
- 如何利用 C# 实现 K 最邻近算法?
- 如何利用 C# 实现 K-D Tree 结构?
- 如何利用 C# + KDTree 实现 K 最邻近算法?
- 如何利用 C# 对神经网络模型进行抽象?
- 如何利用 C# 实现神经网络的感知器模型?
- 如何利用 C# 实现 Delta 学习规则?
- 如何利用 C# 爬取 One 持有者返利数据!
- 如何利用 C# 爬取BigOne交易所的公告!
- 如何利用 C# 爬取 ONE 的交易数据?
- 如何利用 C# 爬取「京东 - 计算机与互联网图书销量榜」!
- 如何利用 C# 爬取「当当 - 计算机与互联网图书销量榜」!
- 如何利用 C# 爬取「猫眼电影专业版:票房」数据!
- 如何利用 C# 爬取「猫眼电影:国内票房榜」及对应影片信息!
- 如何利用 C# 爬取带 Token 验证的网站数据?