今天的题都是链表相关的题
203. 移除链表元素
这道题还是比较简单的,用双指针来做
/**
* 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 removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1);
ListNode cur = head;
ListNode pre = dummy;
dummy.next = cur;
while(cur != null) {
if(cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}
}
707. 设计链表
这道题之前没做过,是模拟题,我是用单链表的思路来解决的,要注意index是从0开始的
class MyLinkedList {
class ListNode {
int val;
ListNode next;
ListNode(){}
ListNode(int _val) {
this.val = _val;
}
}
int size;
//虚拟头节点
ListNode dummyHead;
public MyLinkedList() {
this.size = 0;
dummyHead = new ListNode(-1);
}
public int get(int index) {
if(index < 0 || index >= size) {
return -1;
}
ListNode cur = dummyHead;
for(int i = 0; i <= index; i++) {
cur = cur.next;
}
return cur.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++;
ListNode node = new ListNode(val);
ListNode cur = dummyHead;
for(int i = 0; i < index; i++) {
cur = cur.next;
}
node.next = cur.next;
cur.next = node;
}
public void deleteAtIndex(int index) {
if(index >= size || index < 0) {
return;
}
size--;
if(index == 0) {
dummyHead = dummyHead.next;
return;
}
ListNode cur = dummyHead;
for(int i = 0; i < index; i++) {
cur = cur.next;
}
cur.next = cur.next.next;
}
}
/**
* 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) {
return recur(head, null);
}
private ListNode recur(ListNode cur, ListNode pre) {
if(cur == null)return pre;
ListNode res = recur(cur.next, cur);
cur.next = pre;
return res;
}
}