代码随想录算法训练营第三天| 203.移除链表元素 || 707.设计链表 || 206.反转链表
203.移除链表元素
链接
加个头节点会比较简单
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode pre = new ListNode();
pre.next = head;
ListNode res = pre;
while(res.next!=null){
if(res.next.val==val){
res.next = res.next.next;
}else{
res = res.next;
}
}
return pre.next;
}
}
707.设计链表
链接
不要忘记判断输入非法的情况
class MyLinkedList {
int size;
ListNode head;
public MyLinkedList() {
head = new ListNode(0);
size = 0;
}
public int get(int index) {
if(index<=size-1){
ListNode temp = head;
for(int i=0;i<=index;i++){
temp=temp.next;
}
return temp.val;
}
return -1;
}
public void addAtHead(int val) {
ListNode pre = head;
ListNode curr = new ListNode(val);
curr.next = head.next;
head.next = curr;
while(pre.next!=null){
pre = pre.next;
}
size++;
}
public void addAtTail(int val) {
ListNode last = new ListNode(val);
ListNode temp = head;
while(temp.next!=null){
temp = temp.next;
}
temp.next = last;
size++;
}
public void addAtIndex(int index, int val) {
if(index<=size){
ListNode temp = head;
for(int i=0;i<index;i++){
temp=temp.next;
}
ListNode curr = new ListNode(val);
curr.next = temp.next;
temp.next = curr;
size++;
}
}
public void deleteAtIndex(int index) {
if(index<=size-1){
ListNode temp = head;
for(int i=0;i<index;i++){
temp=temp.next;
}
temp.next = temp.next.next;
size--;
}
}
}
class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val){
this.val = val;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/
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) {
if(head==null||head.next==null){
return head;
}
ListNode last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
}