【LeetCode】C# 24、Swap Nodes in Pairs
来源:互联网 发布:windows清理助手在哪儿 编辑:程序博客网 时间:2024/06/08 12:11
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.
把链表中中的值两两调换。
思路:每两个为一组,定义prev指向被操作组前一个,l1,l2指向两个操作数,next指向下一个。在四个指针结合下完成翻转。
/** * 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; ListNode fakeHead = new ListNode(5); fakeHead.next = head; ListNode l1; ListNode l2; ListNode prev = fakeHead; ListNode ret = head.next; ListNode next = head; while(next != null && next.next != null){ l1 = next; l2 = next.next; next = next.next.next; l1.next = next; l2.next = l1; prev.next = l2; prev = l1; } return ret; }}
阅读全文
0 0
- 【LeetCode】C# 24、Swap Nodes in Pairs
- LeetCode(24)Swap Nodes in Pairs
- [LeetCode 24] Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs
- LeetCode | #24 Swap Nodes in Pairs
- [Leetcode 24 链表]Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- 【leetcode】【单链表】【24】Swap Nodes in Pairs
- Leetcode 24 Swap Nodes in Pairs
- Swap Nodes in Pairs - LeetCode 24
- LeetCode 24 - Swap Nodes in Pairs
- leetcode 24 -- Swap Nodes in Pairs
- LeetCode 24:Swap Nodes in Pairs
- leetcode-24Swap Nodes in Pairs
- leetcode 24: Swap Nodes in Pairs
- Leetcode#24 Swap Nodes in Pairs
- LeetCode 24: Swap Nodes in Pairs
- LeetCode(24) Swap Nodes in Pairs
- springMVC中的controller层
- Hibernate-day03 Hibernate注解开发
- apache web 服务器
- 音视频开发的技术要点 音视频SDK的应用
- 关于Python第三方库安装失败问题的解决方案
- 【LeetCode】C# 24、Swap Nodes in Pairs
- 权限管理系统 ThreadLocal的使用:在同一线程中获取用户信息
- C++学习之对string流的初步认识
- 基于akka与scala实现一个简单rpc框架
- HTML5
- Linux学习之用户,组的基本操作
- Leetcode-Set Matrix Zeroes
- alloy-ui 2.0.0 图片轮播
- angularjs的二种数据绑定