题目:LeetCode 203.移除列表元素
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7
输出:[]
提示:
列表中的节点数目在范围 [0, 104] 内
1 <= Node.val <= 50
0 <= val <= 50
代码:
/** * 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; } if(head == null) return null; ListNode cur = head.next; ListNode prev = head; while(cur != null) { if(cur.val == val) { prev.next = cur.next; } else { prev = cur; } cur = cur.next; } return head; } }
思考:
这道题很简单,注意边界和判空吧。
题目:206.反转链表
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
代码:
/** * 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 || head.next == null) return head; ListNode newhead = null; ListNode cur = head; //头插新节点 while(cur != null) { ListNode tmp = cur; cur = cur.next; tmp.next = newhead; newhead = tmp; } return newhead; } }
思考:
这个也很简单,头插法既简单又好理解。根据尾插理解头插,尾插就是找个新的尾,头插就是找个新的头。等二刷的时候再看什么双指针,递归法吧。