203. 移除链表元素
状态:完成
该题关键点是一个dummyNode如果没有他头节点的移除上会要做一个特殊处理,使用两个指针去进行链表节点的删除。
public ListNode removeElements(ListNode head, int val) {
if(head==null) return head;
ListNode dummyNode=new ListNode(-1);
dummyNode.next=head;
ListNode preNode = dummyNode;
ListNode curNode = head;
while(curNode!=null){
if(curNode.val==val){
preNode.next=curNode.next;
curNode=preNode.next;
}else{
preNode=curNode;
curNode=curNode.next;
}
}
return dummyNode.next;
}
707. 设计链表
状态:完成
这题不是一次性完成的,在写代码中间有些问题没想清楚,到最后提交的时候才急急忙忙的找是哪里出现的问题。我觉得主要问题出现在头节点以及删除节点时的下标异常问题我没有做分类讨论。
class MyLinkedList {
int val;
MyLinkedList next;
MyLinkedList head;
int len;
public MyLinkedList() {}
MyLinkedList(int val){ this.val=val;}
MyLinkedList(int val,MyLinkedList next){
this.val=val;
this.next=next;
}
public int get(int index) {
if(head==null) return -1;
MyLinkedList list=head;
for(int i=0;i<index;i++){
if(list==null) return -1;
System.out.println(list.val);
list=list.next;
}
return list==null?-1:list.val;
}
public void addAtHead(int val) {
MyLinkedList super_head= new MyLinkedList(val,head);
this.head=super_head;
this.len++;
}
public void addAtTail(int val) {
MyLinkedList node = this.head;
MyLinkedList tail= new MyLinkedList(val,null);
if(head==null){
this.head=tail;
this.len++;
return;
}
while(node.next!=null){
node=node.next;
}
node.next=tail;
this.len++;
}
public void addAtIndex(int index, int val) {
if(index==0){
addAtHead(val);
return;
}
if(index>len) return;
MyLinkedList preNode = this.head;
for(int i=0;i<index-1;i++){
preNode = preNode.next;
}
MyLinkedList node = new MyLinkedList(val,preNode.next);
preNode.next=node;
this.len++;
}
public void deleteAtIndex(int index) {
MyLinkedList dummyNode=new MyLinkedList(-1);
dummyNode.next=this.head;
MyLinkedList preNode = dummyNode;
MyLinkedList curNode = this.head;
if(len-1<index) return;
for(int i=0;i<index;i++){
preNode=preNode.next;
curNode=curNode.next;
}
preNode.next=curNode.next;
this.head=dummyNode.next;
this.len--;
}
}
206. 反转链表
状态:完成
这题比较简单了,只要前后两个节点翻转就行了一直遍历下去。
public ListNode reverseList(ListNode head) {
if(head==null) return head;
if(head.next==null) return head;
ListNode node = head;
ListNode preNode =null;
while(node!=null){
ListNode temp = node.next;
node.next=preNode;
preNode=node;
node=temp;
}
return preNode;
}
感想:今天用了3个小时进行算法的练习,中间有点分神(鸟叔去找界王修炼了/(ㄒoㄒ)/~~)。今天对于链表的理解更深了,也掌握了如果头节点要分类讨论的情况下可以使用一个dummyNode的哨兵节点去监控,希望这次刷算法能坚持下来,加油。