数据结构与算法 链表篇之两两交换链表中的节点

题目链接:. - 力扣(LeetCode)

思路一:数学逻辑,由于链表结构比较难操作,将其先放入集合或者数组中,方便处理,随后两两交换,如果后面元素不够交换了,则最后一个元素不用交换。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }else{
            List<Integer> list =new ArrayList();
            while(head!=null){
                list.add(head.val);
                head=head.next;
            }
            int[] arr=new int[list.size()];
            for(int i=0;i<list.size();i=i+2){
                int j=i+1;
                if(j==list.size()){
                    arr[i]=list.get(i);
                    break;
                }
                arr[i]=list.get(j);
                arr[j]=list.get(i);
            }
            ListNode res=new ListNode(0);
            ListNode cur=res;
            for(int item:arr){
                ListNode node=new ListNode(item);
                cur.next=node;
                cur=cur.next;
            }
            return res.next;
        }

    }
}

思路二:利用指针操作原链表,需要注意的是原链表元素个数是奇数还是偶数,这将影响到循环终止条件,并且一定是双与而不是双或。其中双或主要是为了锁住原链表元素个数为奇数个的情况。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }else{
        ListNode dummy=new ListNode(0);
        dummy.next=head;
        ListNode cur=dummy;
        while(cur.next!=null&&cur.next.next!=null){
            ListNode tmp=cur.next;
            ListNode tmp1=cur.next.next.next;
            cur.next=cur.next.next;
            cur.next.next=tmp;
            tmp.next=tmp1;
            cur=cur.next.next;
        }
        return dummy.next;
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值