public class ListNode {
// 结点的值
int val;
// 下一个结点
ListNode next;
// 节点的构造函数(无参)
public ListNode() {
}
// 节点的构造函数(有一个参数)
public ListNode(int val) {
this.val = val;
}
// 节点的构造函数(有两个参数)
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
//203.移除链表元素
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null){
return head;
}
//设置虚拟节点;
ListNode dummy = new ListNode(-1, head);//虚拟节点值为 -1,并且将原链表的头部节点连接到虚拟节点之后
//定义了两个指针 pre 和 cur,分别用来表示当前节点和前一个节点
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.设计链表
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);
}
//获取第index个节点的数值,index是从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;
}
}