从这篇开始了解链表的一些基本的操作。
这道题目我直接对链表指针head进行操作,其实是不对的,按照命名的规范,应该重新起一个移动指针的名字cur(current)
本题感悟:涉及指针域的操作,慎用head.next.next;
题目来源 https://leetcode-cn.com/problems/remove-linked-list-elements/
/**
* 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) {
ListNode dummyNode;
ListNode pre;
dummyNode = new ListNode(-1, head);
pre = dummyNode;
while(head != null){
if(head.val != val){
pre = head;
}else{
pre.next = head.next;
}
head = head.next;
}
return dummyNode.next;
}
}
//head.next有可能已经是null了,所以null没有null.next
//所以涉及指针域的操作,慎用head.next.next;