题目链接:203. 移除链表元素 - 力扣(LeetCode)
/**
* 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 head;
}
ListNode tempHead = new ListNode(1, head);
ListNode cur = head;
ListNode pre = tempHead;
while (cur != null){
if (cur.val == val){
pre.next = cur.next;
}else{
pre = cur;
}
cur = cur.next;
}
return tempHead.next;
}
}
主要注意是否设计虚拟头结点。
考研时数据结构链表最基本的题
/**
* 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) {
ListNode pre = null;
ListNode cur = head;
ListNode temp = null;
while(cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
双指针+零时指针或递归(适合递归掌握比较熟练的写)