Swap Two Nodes in Linked List
来源:互联网 发布:tomcat启动端口号 编辑:程序博客网 时间:2024/06/06 05:53
Given a linked list and two values v1 and v2. Swap the two nodes in the linked list with values v1 and v2. It's guaranteed there is no duplicate values in the linked list. If v1 or v2 does not exist in the given linked list, do nothing.
Notice
You should swap the two nodes with values v1 and v2. Do not directly swap the values of the two nodes.
Example
Given 1->2->3->4->null
and v1 = 2
, v2 = 4
.
Return 1->4->3->2->null
.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { /** * @param head a ListNode * @oaram v1 an integer * @param v2 an integer * @return a new head of singly-linked list */ public ListNode swapNodes(ListNode head, int v1, int v2) { if(head == null || head.next == null) { return head; } ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; ListNode first = null, second = null; while(head.next != null) { if(head.next.val == v1) { first = head; } else if(head.next.val == v2) { second = head; } head = head.next; } if(first == null || second == null) { return dummy.next; } if(second.next == first) {//make sure that the first is always before the second ListNode temp = second; second = first; first = temp; } if(first.next == second) {//if these two nodes are adjacent ListNode third = second.next; first.next = third; ListNode temp = third.next; third.next = second; second.next = temp; } else { ListNode node1 = first.next; ListNode post1 = node1.next; ListNode node2 = second.next; ListNode post2 = node2.next; first.next = node2; node2.next = post1; second.next = node1; node1.next = post2; } return dummy.next; }}
0 0
- Swap Two Nodes in Linked List
- LintCode:Swap Two Nodes in Linked List
- #511 Swap Two Nodes in Linked List
- Swap Two Nodes in Linked List
- [LintCode]Swap Two Nodes in Linked List
- Swap Two Nodes in Linked List
- 24. Swap Nodes in Pairs(Linked List)
- 511.Swap Two Nodes in Linked List-交换链表当中两个节点(中等题)
- 2.swap-two-nodes-in-linked-list(交换链表中的两个结点)
- [LintCode] Swap Two Nodes in Linked List 交换链表中的两个结点
- LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)(Linked List)
- Posts Tagged 【List】Swap Nodes in Pairs
- [leetcode][list] Swap Nodes in Pairs
- 24. Swap Nodes in Pairs leetcode(list)
- Given a linked list, swap values inside nodes.
- 【LeetCode24】. Swap Nodes in Pairs Add to List
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- C语言动态二维数组实现矩阵的相乘
- snoopy类
- iOS 代码调用打电话
- Fedora 25 Workstation 安装指南
- Ionic 常见问题及解决方案
- Swap Two Nodes in Linked List
- yii框架搜索后分页
- C++ operator= 注意事项
- 透明度百分和六进制对比表
- linux 密码输入回显星号
- 用AES来加密和解密文件
- webService怎么调用Service
- smartctl /dev/sda1 -a,linux硬盘信息查询
- Appium-1 Appium环境搭建