移除链表元素
题目链接:https://leetcode.cn/problems/remove-linked-list-elements/
这一题只看了,虚指针这种。感觉虚指针好牛,能省去再对第一个节点分类的步骤。
class Solution {
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;//返回head
}
}
设计链表
题目链接:https://leetcode.cn/problems/design-linked-list/
看题解学会代码复用思想。判断条件写好,能省去很多代码。看着题解才能写出来。
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 currtNode = head;
for(int i = 0;i <= index;i++){
currtNode = currtNode.next;
}
return currtNode.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 pred = head;
for(int i =0;i < index;i++){
pred = pred.next;
}
ListNode toAdd = new ListNode(val);
toAdd.next = pred.next;
pred.next = toAdd;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size){
return;
}
size--;
if (index == 0){
head = head.next;
return;
}
ListNode pred =head;
for(int i = 0;i < index; i++){
pred = pred.next;
}
pred.next = pred.next.next;
}
}
反转链表
题目链接:https://leetcode.cn/problems/reverse-linked-list/submissions/
对着写了一遍,明天接着看
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp = null;
while(cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return prev;
}
}
本文介绍了如何在链表中删除指定元素,利用虚指针简化操作;设计链表结构并实现常见操作,如添加、获取和删除元素;以及如何反转链表。这些是基于LeetCode的编程挑战。
761

被折叠的 条评论
为什么被折叠?



