代码随想录算法训练营第三天 | LeetCode203 移除链表元素、LeetCode 707 设计链表、LeetCode 206 反转链表
)
链表中的元素在计算机内存的分布不是连续的是分散的, 链表是靠指针连接在一起的, 所以要对链表中的元素做操作时, 应当利用这种特性, 还有链表特有的删除和插入操作
LeetCode203 移除链表元素
题目链接
靠着元素之间的指针来遍历所有元素
public ListNode removeElements(ListNode head, int val) {
while(head != null && head.val == val){
head = head.next;
}
if(head == null){
return null;
}
ListNode prev = head;
ListNode cur = head.next;
while(cur != null){
if(cur.val == val){
prev.next = cur.next;
}else{
prev = prev.next;
}
cur = cur.next;
}
return head;
}
LeetCode 707 设计链表
public class MyLinkedList {
int size = 0;
LinkedListByMe head;
public static class LinkedListByMe{
int val;
LinkedListByMe next;
public LinkedListByMe(int val){
this.val = val;
}
public LinkedListByMe(int val, LinkedListByMe next){
this.val = val;
this.next = next;
}
}
public MyLinkedList(){
}
public int get (int index){
LinkedListByMe cur = head;
if(index >size -1 ||index <0){
return -1;
}
while (index > 0){
cur = cur.next;
index--;
}
return cur.val;
}
public void addAtIndex(int index, int val){
if(index > size){
return;
}
LinkedListByMe dummy = new LinkedListByMe(-1,head);
LinkedListByMe cur = dummy;
LinkedListByMe temp = new LinkedListByMe(val);
while ( index > 0){
cur = cur.next;
index--;
}
temp.next = cur.next;
cur.next = temp;
head = dummy.next;
size++;
}
public void addAtHead(int val){
addAtIndex(0, val);
}
public void addAtTail(int val){
addAtIndex(size, val);
}
public void deleteAtIndex(int index){
if (index <0 || index>= size){
return;
}
LinkedListByMe dummy = new LinkedListByMe(-1, head);
LinkedListByMe cur = dummy;
while (index > 0){
cur = cur.next;
index--;
}
cur.next = cur.next.next;
head = dummy.next;
size--;
}
}
LeetCode 206 反转链表
题目链接
使用方法: 递归
public ListNode reverseList(ListNode head) {
return reverseNode(null, head);
}
public ListNode reverseNode(ListNode prev, ListNode cur){
if(cur == null) {
return prev;
}else{
ListNode temp = cur.next;
cur.next = prev;
return reverseNode(cur, temp);
}
}
今日总结:不要被表象所迷惑, 要知道为什么要这样做
要去了解为什么要这样做