203.移除链表元素
建议: 本题最关键是要理解 虚拟头结点的使用技巧,这个对链表题目很重要。
题目链接/文章讲解/视频讲解::代码随想录
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0); // 创建一个虚拟头节点
dummy.next = head;
ListNode hr = dummy;
while (hr.next != null) {
if (hr.next.val == val) {
hr.next = hr.next.next;
} else {
hr = hr.next;
}
}
return dummy.next; // 返回虚拟头节点的下一个节点,即新的头节点
}
}
707.设计链表
建议: 这是一道考察 链表综合操作的题目,不算容易,可以练一练 使用虚拟头结点
题目链接/文章讲解/视频讲解:代码随想录
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;
}
}
public class MyLinkedList {
/**
* 链表个数
*/
int size;
/**
* 虚拟头节点
*/
ListNode dummy;
public MyLinkedList() {
size = 0;
dummy = new ListNode(0);
}
public int get(int index) {
//判断index是否有效
if(index<0 || index>=size){
return -1;
}
//注意这里是获取节点,因此不需要找到上一个节点,索引cur是dummy.next,
//上一个节点的话,cur = dummy就可以了
//因为=dummy的时候,cur正好是第0个节点的上一个
ListNode cur = dummy.next;
while(index-->0){
cur = cur.next;
}
return cur.val;
}
public void addAtHead(int val) {
ListNode newHead = new ListNode(val);
newHead.next = dummy.next;
dummy.next = newHead;
size++;
}
public void addAtTail(int val) {
ListNode cur = dummy;
while(cur.next.next!=null){
cur = cur.next;
}
ListNode newListNode = new ListNode(val);
newListNode.next = null;
cur.next = newListNode;
size++;
}
public void addAtIndex(int index, int val) {
ListNode cur = dummy;
while(index-->0){
cur = cur.next;
}
ListNode newListNode = new ListNode(val);
newListNode.next = cur.next;
cur.next = newListNode;
size++;
}
public void deleteAtIndex(int index) {
ListNode cur = dummy;
while(index-->0){
cur= cur.next;
}
cur.next = cur.next.next;
size--;
}
}
206.反转链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur=head;
ListNode pre=null;
ListNode tempt=null;
while(cur!=null)
{
tempt=cur.next;
cur.next=pre;
pre=cur;
cur=tempt;
}
return pre;
}
}
题目链接/文章讲解/视频讲解:代码随想录