day 7 翻转链表||两两交换链表中的节点||删除链表的倒数第n个节点

题目链接

力扣

看题目后

没啥思路。链表还是不太熟悉,没什么印象,不会就看题解

看题解后

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
// 链表 没思路
// 看完题解后
// 如果链表没有节点或一个节点 直接返回 不用翻转
if(!head||!head.next) return head

// 链表有多个节点 需要翻转
// JS如何定义一个空指针 怎么定义指针指向头结点 

let pre = null,temp = null,cur = head
while(cur){
temp = cur.next
cur.next = pre
pre = cur
cur=temp//遍历 cur = cur.next
}
return pre
};

知道思路,但不知道怎么实现。

定义一个cur = head,pre=null,temp=null

while(cur)

用temp 存储每次遍历的节点,

从头节点开始遍历,

让头节点的指针指向null 头节点后一个节点的next指向头节点,依次遍历。

遇到的困难

js如何定义空指针 定义指针指向头节点

let cur=null,temp=head

两两交换链表中的节点

力扣

看题后

没啥思路

看题解后

使用虚拟头节点,方便一点,不用单独考虑头节点的情况

const ret = ListNode(0,head)

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function(head) {
// 如果链表没有节点 或节点只有一个 直接返回 头节点

// 多个节点 没有思路
// 使用虚拟头节点 不用考虑头节点的情况
let ret = new ListNode(0,head),temp=ret
while(temp.next&&temp.next.next){
    let cur = temp.next.next,pre=temp.next;
    // pre.next=cur.next;
    // cur.next=pre
    // temp.next=cur;
    // temp=pre;
    pre.next=cur.next//步骤3 放下面的话 cur已经变了
    temp.next = cur
    cur.next=pre
    temp=pre//移动两位,准备下一轮交换
    
}
return ret.next
};

 步骤1  头节点指向第二个元素,2 第二个元素指向第一个元素  3第一个元素指向第二个元素后一个元素

虚拟头节点往后移动两位

删除链表的倒数第n个节点

卡了比较长时间,写的时候思路没有理清,出错就只对照代码,不去用案例思考

走n+1步 和n步条件是是不一样的

收获

链表了解的又多了一点

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值