提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
提示:这一部分我开始学习链表。
一、链表基础
二、203. 移除链表元素
无论是添加不添加虚拟节点,cur和pre指针都会在原链表的某一个位置对原链表的某一个节点x 的x.next进行修改以此达到删除元素的目的。
1.方法一
/**
* 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) {
// 删除头结点
while(head!=null && head.val==val){
head=head.next;
}
// 删除非头结点
ListNode cur=new ListNode();
cur=head;
while(cur!=null && cur.next!= null){
if(cur.next.val==val){
cur.next=cur.next.next;
}else{
cur=cur.next;
}
}
return head;
}
}
2. 方法二: 添加虚拟节点
dummy 节点和 head节点不动,pre和cur节点遍历,cur永远比pre早一格类似双指针,符合要求的cur节点会赋值在pre节点,最终dummy指向的head节点(dummy.next)
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1,head);
ListNode pre= dummy;
ListNode cur = head;
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
} else{
pre=cur;
}
cur=cur.next;
}
return dummy.next;
}
}
三、707. 设计链表
- 重点在于利用虚拟头节点和while循环,找到第n-1节点位置,进行操作。
- 注意在add函数里加入size++语句,因为这个链表每一个元素都需要利用add函数添加(每加一个元素size都会++)
- 同理delet函数含size–
class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val) {
this.val=val;
}
}
class MyLinkedList {
int size;
ListNode head;
public MyLinkedList() {
size=0;
head=new ListNode(0);
}
public int get(int index) {
ListNode cur = head;
if(index<0 || index>=size){
return -1;
}else{
while(index>=0){
cur=cur.next;
index--;
}
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) {
ListNode dummy = head;
ListNode cur = dummy;
if(index>size){
return;
}
if (index < 0) {
index = 0;
}
size ++;
while(index>0){
cur=cur.next;
index--;
}
ListNode x = new ListNode(val);
x.next=cur.next;
cur.next = x;
}
public void deleteAtIndex(int index) {
ListNode dummy = head;
ListNode cur = dummy;
if(index<0 || index>=size){
return;
}
size --;
while(index>0){
cur=cur.next;
index--;
}
cur.next = cur.next.next;
}
}
四、206. 反转链表
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
ListNode tmp = null;
while(cur!=null){
tmp=cur.next;
cur.next=prev;
prev=cur;
cur=tmp;
}
return prev;
}
}