代码随想录算法训练营第三天|203.移除链表元素、707.设计链表、206.反转链表

203.移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

解题思路

感觉这套题目算是入门题?我一开始用的for遍历,放在一个新的ListNode里面,也是可以正常AC的。但是如果要想到虚拟节点,就可能动点脑子了。

解法1
public ListNode removeElements(ListNode head, int val) {
	if (head == null) {
		return head;
	}
	ListNode dummy =new ListNode(-1, head);
	ListNode pre = dummy;
	ListNode cur = head;
	while (cur != null) {
		if (cur.val == val) {
			pre.next = cur.next;
		} else {
			pre = cur;
		}
		cur = cur.next;
	}
	return dummy.next;
}

707.设计链表

你可以选择使用单链表或者双链表,设计并实现自己的链表。

解题思路

很难想到,或者说很难成体系的完成这类设计题目。需要时常学习或者复习。

解法1
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }
}

class MyLinkedList {
    int size;
    ListNode head;

    public MyLinkedList() {
        size = 0;
        head = new ListNode(0);
    }

    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }
        ListNode cur = head;
        for (int i = 0; i <= index; i++) {
            cur = cur.next;
        }
        return cur.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    public void addAtTail(int val) {
        addAtIndex(size, val);
    }

    public void addAtIndex(int index, int val) {
        if (index > size) {
            return;
        }
        if (index < 0) {
            index = 0;
        }
        size++;
        ListNode pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        ListNode toAdd = new ListNode(val);
        toAdd.next = pre.next;
        pre.next = toAdd;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }
        size--;
        if (index == 0) {
            head = head.next;
            return;
        }
        ListNode pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        pre.next = pre.next.next;

    }
}

206.反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

解题思路

很老,但是考察也很多的题目。很经典。遍历和递归都要学会,这个需要看视频学习。

解法1
public ListNode reverseList(ListNode head) {
	ListNode pre = null;
	ListNode cur = head;
	ListNode tmp = null;
	while (cur != null) {
		tmp = cur.next;
		cur.next = pre;
		pre = cur;
		cur = tmp;
	}
	return pre;
}
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

君若雅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值