[路飞]_1721.交换链表中的节点(双指针)

127 阅读1分钟

「这是我参与11月更文挑战的第10天,活动详情查看:2021最后一次更文挑战

LeetCode1721.交换链表中的节点

题目要求

给你链表的头节点 head 和一个整数 k

交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。

示例

输入:head = [1,2,3,4,5], k = 2输出:[1,4,3,2,5]
思路

1.声明cur(用来遍历链表的指针),first(第一个指针),second(第二个指针),count = 1 (链表 从 1 开始索引),当cur指针的一下个值不为null的时候cur指针不断向下遍历,同时count=k的时候second向下遍历,当cur == null的时候停止遍历
var swapNodes = function(head, k) {    
    let cur = head; // 用来遍历整个链表    
    let first = head; // 用来找一个值    
    let second = head; // 用来找第二个值    
    let count = 1; // 用来判断first 和 second是否需要向下遍历    
    let temp; // 用来做交换的第三变量    
    while (cur.next != null) {        
        if (count < k) {            
            first = first.next;        
        } else {            
            second = second.next;        
        }        
        count++;        
        cur = cur.next;    
    }
};
2.交换first和second的值
var swapNodes = function(head, k) {    
    ...    
    temp = first.val;    
    first.val = second.val;    
    second.val = temp;
};

完整代码

var swapNodes = function(head, k) {    
    let cur = head;    
    let first = head;    
    let second = head;    
    let count = 1;    
    let temp;    
    while (cur.next != null) {        
        if (count < k) {            
        first = first.next;        
    } else {            
        second = second.next;        
    }        
    count++;        
    cur = cur.next;    
    }    
    temp = first.val;    
    first.val = second.val;    
    second.val = temp;    
    return head;
};