【Java】LeetCode进阶之路(Swap Nodes in Pairs)

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.

题目;根据给出的例子,可以很容易理解题意,把一个链表每两个节点调换位置。

思路:链表位置不好调换,所以先把这个数据放到一个数组里,这样就容易换位置了,换完之后在输出新的链表即可。

public class Solution {
    public ListNode swapPairs(ListNode head) {
        List<Integer> list = new ArrayList<Integer>();
        ListNode node = new ListNode(0);
        ListNode h = node;
        while(head != null){
            list.add(head.val);
            head = head.next;
        }
        int[] nums = new int[list.size()];
        for(int i = 0; i<list.size();i = i+2){
            if(i + 1 > list.size() -1) {
                nums[i] = list.get(i);
            }else {
                nums[i] = list.get(i+1);
                nums[i+1] = list.get(i);
            }
        }
        for(int i = 0;i < nums.length;i++){
            ListNode n = new ListNode(nums[i]);
            h.next = n;
            h = h.next;
        }
        
        return node.next;
    }
}

7.26更新

这道题目涉及到链表,肯定是希望用指针的思想来做,下面这种方法就是用到了指针,通过指针指向不同的位置来更换节点的顺序。

<span style="font-size:18px;">public ListNode swapPairs(ListNode head) {
        if(head == null) return null;
        if(head.next == null) return head;
        
        ListNode first = new ListNode(-1);
        first.next = head;
        ListNode ptr1 = first;
        ListNode ptr2 = first.next;
        while(ptr1 != null && ptr2 != null && ptr2.next != null) {
            ListNode nextNode = ptr2.next.next;
            ptr1.next = ptr2.next;
            ptr1.next.next = ptr2;
            ptr2.next = nextNode;
            ptr1 = ptr2;
            ptr2 = nextNode;
        }
        return first.next;
    }</span>



种一棵树最好的时间是十年前,其次是现在!

明天必须把深度优先算法整理一遍!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值