[Leetcode] Swap Nodes in Pairs (Java)
来源:互联网 发布:怎么加盟淘宝实体店 编辑:程序博客网 时间:2024/06/14 07:08
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.
头脑发热,保存了好多的中间ListNode变量。。
public class SwapNodesinPairs {static class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}} public ListNode swapPairs(ListNode head) { if(head==null) return null; ListNode index = head; int k=0; while(index!=null){ k++; index=index.next; } index = head; ListNode res = new ListNode(-1); res.next = head; if(k%2==0){ ListNode pre = null; ListNode post = null; ListNode temp = res; while(index!=null){ pre = index; post = index.next; index = index.next.next; temp.next = post; post.next = pre; pre.next = index; temp = pre; } }else { ListNode pre = null; ListNode post = null; ListNode temp =res; while(index.next!=null){ pre = index; post = index.next; index = index.next.next; if(index!=null) { temp.next= post; post.next = pre; pre.next = index; temp = pre; } } } return res.next; } public static void main(String[] args) {ListNode head = new ListNode(1);ListNode l2 = new ListNode(2);head.next = l2;head = new SwapNodesinPairs().swapPairs(head);System.out.print(head.val);head=head.next;while(head!=null) {System.out.print("->"+head.val);head=head.next;}}}
0 0
- [Leetcode] Swap Nodes in Pairs (Java)
- leetcode Swap Nodes in Pairs java实现
- [LeetCode][Java] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs [java]
- 24. Swap Nodes in Pairs -leetcode-java
- (Java)LeetCode-24. Swap Nodes in Pairs
- [LeetCode-Java]24. Swap Nodes in Pairs
- [leetcode]24. Swap Nodes in Pairs(java)
- [LeetCode] 24. Swap Nodes in Pairs java
- leetcode Swap Nodes in Pairs(Java)
- Swap Nodes in Pairs leetcode java
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- Leetcode: Swap nodes in pairs
- [LeetCode]Swap Nodes in Pairs
- 21分钟 MySQL 入门教程
- JW Player 使用 RTMP 流
- linux设备驱动归纳总结(三):4.ioctl的实现
- linux特殊权限SUID,SGID和SBIT实例演示
- 享元模式
- [Leetcode] Swap Nodes in Pairs (Java)
- 常用的android弹出对话框
- tcp握手
- DIV+CSS中的一些常见标签
- 编程珠玑 第二章 习题5
- js高级程序设计学习笔记——基本概念
- C++内存分配
- 【CUDA编程】 CUDA编程初始
- C#中的委托与事件(一)