203、移除链表元素
注:由于链表的性质,移除 当前节点 需要获取它的 前一个节点(pre) 才能利用 (pre.next = pre.next.next) 将当前节点置空,所以就需要创建 虚拟头节点(dummyhead) 防止 头节点(head) 置空。
代码如下:
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyhead = new ListNode(0);
dummyhead.next = head; // 将虚拟头节点指向头节点连接链表
ListNode temp = dummyhead;
while(temp.next != null){
if(temp.next.val == val){
temp.next = temp.next.next;
}else{
temp = temp.next;
}
}
return dummyhead.next;
}
}
由于在后续思考 206、反转链表 使用了递归思想便跳回来思考了一下该题目的递归
递归思想代码如下:
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null){
return head;
}
head.next = removeElements(head.next,val);
if(head.val == val){
return head.next;
}else{
return head;
}
}
}
206、反转链表
反转链表该题已经重复刷了不下5遍,每次都会有迷茫点还是说明没有完全掌握
而每次经常犯错误的一点便是:在进行链表反转时,会忘记存储当前节点的下一个节点导致更新节点时无法继续遍历链表
常规迭代代码如下:
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode pre = null;
ListNode cur = head;
while(cur !=null){
ListNode next_cell = cur.next; // !!!经常出错的地方!!!
cur.next = pre;
pre = cur;
cur = next_cell;
}
return pre;
}
}
而递归代码如下:
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;
}
}
707、设计链表(!!!值得多刷!!!)
对这道题感叹真的太多了,完完全全考察对链表性质的考察,对细节的掌握等等
就算写出来了也不敢说真的理解透彻了
class MyLinkedList {
private ListNode head;
private int size;
public MyLinkedList() {
head = null;
size = 0;
}
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 node = new ListNode(val);
node.next = head;
head = node;
size++;
}
public void addAtTail(int val) {
ListNode node = new ListNode(val);
if (head == null) {
head = node;
} else {
ListNode cur = head;
while (cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
size++;
}
public void addAtIndex(int index, int val) {
if (index > size) {
return;
}
if (index == 0) {
addAtHead(val);
return;
}
ListNode pre = head;
for (int i = 0; i < index - 1; i++) {
pre = pre.next;
}
ListNode node = new ListNode(val);
node.next = pre.next;
pre.next = node;
size++;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
if (index == 0) {
head = head.next;
} else {
ListNode pre = head;
for (int i = 0; i < index - 1; i++) {
pre = pre.next;
}
pre.next = pre.next.next;
}
size--;
}
}