203. 移除链表元素
简单
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
//没有太读懂题,看了解析之后明白了,
小结:
1.LinkedList 链表的结构 ,指针next相连接,链表的定义具有递归的性质
2.删除 或添加,头节点需要单独讨论,或者新建一个dummy头节点
3.删除cur,只需要pre →cur.next(pre.next.next)
4.历遍需要新建一个cur,while(cur.next!=null),cur=cur.next 这样 新建之后就会保留dummy的值,最后return 就是dummy.next 也就是新的head
方法一:dummy head (迭代)
/**
* 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) {
if (head==null){
return null;
}
ListNode dummyHead=new ListNode(0,head);
dummyHead.next=head;
ListNode cur=head;
ListNode pre=dummyHead;
while(cur!=null){
if(cur.val ==val){
pre.next=cur.next;
}else{
pre=cur;
}
cur=cur.next;
}
return dummyHead.next;
}
}
方法2:递归
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
head.next = removeElements(head.next, val); //删除除head以外,等于val的节点
return head.val == val ? head.next : head;
}
}
作者:力扣官方题解
206. 反转链表
简单
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
双指针是逻辑基础,递归还没有太理清楚,等熟悉,熟练了再去理解递归
需要复盘N 次!
/**
* 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){
return null;
}
ListNode pre=null;
ListNode cur=head;
ListNode temp=null;
while(cur!=null){
temp=cur.next;
cur.next=pre;
pre=cur;
cur=temp;
}
return pre;
}
}