题目内容
力扣题目内容如下:题目链接
解题思路与方案
1.利用题目自定义ListNode结构,创建节点元素
如图:
2.方法实现
带头节点链表实现
此处采用的是带头节点的链表实现,创建一个空的头节点,将空的头节点的尾指针指向传入的参数head,进行元素的删除,具体操作内容如下:
public class Solution {
public ListNode removeElements(ListNode head, int val){
ListNode dummeyNode = new ListNode(-1);
dummeyNode.next = head;
ListNode pre = dummeyNode;
while(pre.next != null){
if(pre.next.val == val){
pre.next = pre.next.next;
}else {
pre = pre.next;
}
}
return dummeyNode.next;
}
}
不带头节点链表实现
此处采用的是不到头节点的链表实现,先判断头节点是否为要删除的元素,进行循环删除,直到头节点的元素不是被删除元素,再进行判断该链表是否为空,若为空则返回null,最后当链表不为空时,遍历链表数据,若为要删除的元素,则删除此节点。具体代码实现如下:
public class Soluction {
public ListNode removeElements(ListNode head, int val){
while(head != null && head.val == val){
head = head.next;
}
if (head == null)
return null;
ListNode pre = head;
while(pre.next != null){
if(pre.next.val == val){
pre.next = pre.next.next;
}else {
pre = pre.next;
}
}
return head;
}
}
递归实现元素删除
此方法采用递归实现元素删除,先判断节点是否为空,若为空则返回null,作为递归结束的条件,再通过递归判断返回值元素,若该元素是要被删除的元素,则返回该元素的后一位元素,若不是则返回该元素节点。具体实现内容如下:
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null)
return null;
head.next = removeElements(head.next, val);
return head.val == val? head.next:head;
}
}