Swap Two Nodes in Linked List

本文介绍了一种在链表中通过交换两个指定值的节点位置而非直接交换值的方法。该算法首先创建一个新的头结点简化操作流程,然后查找指定值的前驱节点并进行节点交换,最终返回调整后的链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 注意事项

You should swap the two nodes with values v1 and v2. Do not directly swap the values of the two nodes.

样例

Given 1->2->3->4->null and v1 = 2, v2 = 4.

Return 1->4->3->2->null.

思路:

1、先创建一个新的头结点R_head,并让他指向原来的头结点,这样可以减少很多麻烦;

2、先找到v1、v2的前一个节点,由于有了第一步,无需担心v1或者v2为头结点的情况;

3、找到后交换两次,返回R_head.next。

/**
 * 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) {
        // Write your code here
        ListNode pre1=null,pre2=null,now=null,R_head;
        R_head = new ListNode(-1);
        R_head.next = head;
        now = R_head;
        while(now.next!=null&&(pre1==null||pre2==null)){
            if(pre1==null&&now.next.val==v1){
                pre1 = now;
            }
            else if(pre2==null&&now.next.val==v2){
                pre2 = now;
            }
            now = now.next;
        }
        if(pre1==null||pre2==null)
            return head;
        {
            now = pre1.next;
            pre1.next = pre2.next;
            pre2.next = now;
            
            now = pre1.next.next;
            pre1.next.next = pre2.next.next;
            pre2.next.next = now;
        }
        return R_head.next;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值