当日任务
链表理论基础
203.移除链表元素
707.设计链表
206.反转链表
链表基础理论
何为链表? 链表是通过指针串联在一起的线性结构。链表分为单链表,双链表和循环链表。
203.移除链表元素
题目链接:. - 力扣(LeetCode)
题目逻辑不复杂,复杂主要在2点
1.删除至少有3中场景要考虑,第一是删除链表头,第二是删除链表尾,第三是删除链表居中,本地通过引入dummy虚拟节点,能很好地处理这三种场景;
2.第二是如何在本地构造链表和调试
class Solution {
public ListNode removeElements(ListNode head, int val) {
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 = pre.next;
}
cur = cur.next;
}
return dummy.next;
}
本地构造调试用例:
@Test
public void test() {
//1,2,6,3,4,5,6
ListNode node1 = new ListNode(6, null);
ListNode node2 = new ListNode(5, node1);
ListNode node3 = new ListNode(4, node2);
ListNode node4 = new ListNode(3, node3);
ListNode node5 = new ListNode(6, node4);
ListNode node6 = new ListNode(2, node5);
ListNode node7 = new ListNode(1, node6);
ListNode head = node7;
int target = 6;
ListNode ret = removeElements(head, target);
while(ret != null){
System.out.println("" + ret.val);
ret = ret.next;
}
}
private class ListNode{
int val;
ListNode next;
ListNode() {};
ListNode(int val) { this.val = val; };
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
707.设计链表
题目链接:. - 力扣(LeetCode)
class MyLinkedList {
ListNode head;
int size;
public MyLinkedList() {
size = 0;
head = new ListNode(0); //dummy虚拟节点
}
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) {
ListNode newnode = new ListNode(val);
newnode.next = head.next;
head.next = newnode;
size++;
}
public void addAtTail(int val) {
ListNode newnode = new ListNode(val);
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = newnode;
size++;
}
public void addAtIndex(int index, int val) {
if (index > size) {
return;
}
if (index < 0) {
index = 0;
}
ListNode pre = head;
for (int i = 0; i < index; i++) {
pre = pre.next;
}
ListNode newnode = new ListNode(val);
newnode.next = pre.next;
pre.next = newnode;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
size--;
ListNode pre = head;
for (int i = 0; i < index; i++){
pre = pre.next;
}
pre.next = pre.next.next;
}
}
206.反转链表
题目链接:. - 力扣(LeetCode)
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 pre;
}
}