一、203 移除链表元素
1.题目
https://leetcode-cn.com/problems/remove-linked-list-elements/
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
2.原理
- 初始化一个节点,该节点的下一个指向链表的头结点
- 判断该节点的下一个阶段是否和val相同 相同就用指向next.next来删除节点,否则向下遍历
- 返回初始化的节点,因为可能有原链表被全部删除的情况 [7,7,7] 7
3.代码
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null) return head;
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode cur = newHead;
while(cur.next !=null){
if (cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
//return head;
return newHead.next;
}
}
二、206. 反转链表
1.题目
https://leetcode-cn.com/problems/reverse-linked-list/
2.原理
- 三个指针,cur为当前指针,pre为cur的上一个指针,next为cur的下一个指针
- 先用next将cur.next节点保存起来,因为cur指向pre后,cur到next的联系就断了,不提前保存链表就断了,没办法继续往下走;
- cur指向pre
- cur赋值给pre,pre向前进
- next赋值给cur,cur向前进
- 最后cur指向尾节点的下一个,即null,所以要返回pre
3.代码
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode cur =head;
ListNode pre = null;
ListNode next = null;
while(cur!=null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}