203.移除链表
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode();
dummyHead.next=head;
ListNode curr = dummyHead;
while(curr.next != null){
if(curr.next.val == val){
curr.next = curr.next.next;
}else{
curr=curr.next;
}
}
return dummyHead.next;
}
}
707.设计链表
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
public ListNode() {
}
}
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 curr = head;
for (int i = 0; i <= index ; i++) {
curr = curr.next;
}
return curr.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 curr = head;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
ListNode newNode = new ListNode(val);
newNode.next = curr.next;
curr.next = newNode;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
size--;
if(index == 0){
head = head.next;
return;
}
ListNode curr = head;
for (int i = 0; i < index ; i++) {
curr =curr.next;
}
curr.next=curr.next.next;
}
}
206.反转链表
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return null;
}
if(head.next == null){
return head;
}
ListNode pre = null, cur = head,tmp;
while(cur != null){
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本