代码随想录算法训练营第一天| 203.移除链表元素、206.反转链表、707.设计链表
定义一个单链表
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; }
}
移除链表元素
题目描述
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
- 删除链表中间的元素 1->2->3->4->5 删除元素4
- 直接删除链表的头节点 1->2->3 删除元素1
直接删除法
public ListNode removeElementsDirect(ListNode head, int target) {
//这里使用while 不用if是因为链表可能是1->1->1->2
while(head!=null&&head.val==target){
head=head.next;
}
//移除其他不在是头节点的元素
ListNode curr=head;
while(curr!=null&&curr.next!=null){
if(curr.next.val==target){
//将节点删除
curr.next=curr.next.next;
}else{
// 移动到下一个节点
curr=curr.next;
}
}
return head;
}
虚拟节点法
public ListNode removeElementWithDummyNode(ListNode head, int target) {
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
//使用哑节点可以直接将头节点删除个中间节点的删除合并成一个算法
ListNode curr = dummyNode;
while (curr.next != null) {
if (curr.next.val == target) {
////将节点删除
curr.next = curr.next.next;
} else {
// 移动到下一个节点
curr = curr.next;
}
}
return dummyNode.next;
}
设计链表
单链表
class MyLinkedList {
int size = 0;
ListNode dummy;
public MyLinkedList() {
size = 0;
dummy = new ListNode(0);
}
public int get(int index) {
if (index < 0 || index >= size) {
return -1;
}
ListNode curr = dummy;
while (index-- >= 0) {
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++;//fast modify
ListNode pre = dummy;
while (index-- > 0) {
pre = pre.next;
}
ListNode newNode = new ListNode(val);
newNode.next = pre.next;
pre.next = newNode;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {return;}
size--;
if (index == 0) {
dummy = dummy.next;
return;
}
ListNode pre = dummy;
while (index-- > 0) {
pre = pre.next;
}
pre.next = pre.next.next;
}
}
反转链表
题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
public ListNode reversListNode(ListNode head) {
ListNode pre=null;
ListNode curr=head;
ListNode temp;
while (curr!=null){
temp=curr.next; //save the next node
curr.next=pre;
pre=curr;
curr=temp;
}
return pre;
}