- 新建一个链表将所有值不是val的结点进行尾插操作
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode result = null;
ListNode cur = head;
ListNode last=null;//用来记录当前链表的最后一个结点
while (cur != null) {
if (cur.val == val) {
cur=cur.next;
continue;//结束本次循环
}
else
{
ListNode next=cur.next;
cur.next=null;
if(result==null){//进行尾插时考虑链表是否为空
result=cur;
}
else{
last=last.next;//查找最后一个结点
}
last=cur;
cur=next;
}
}
return result;
}
}
2.设置两个引用,并对第一个结点做特殊处理
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode prev = null;//始终指向cur的前驱结点
ListNode cur = head;
while (cur != null)
{
if (cur.val == val) {
if (cur == head) {
head = cur.next;
cur = cur.next;//对头结点进行处理,防止要删除的结点出现在第一个位置
} else {
prev.next = cur.next;//若不对头结点进行处理,prev会报错
cur = cur.next;
}
}
else {
prev = cur;
cur = cur.next;
}
}
return head;
}
}
3.设置两个引用,跳过第一个节点最后处理
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode prev = null;
ListNode cur = head;
while (cur != null)
{
if (cur.val == val)
{
prev.next = cur.next;
cur = cur.next;
}
else
{
prev = cur;
cur = cur.next;
}
}
if(head.val==val)
head=head.next;
return head;
}
}//对头结点进行最后处理
4.设置两个引用,并强行加一个前驱结点
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode tmpHead = new ListNode(-1);//强行加一个前驱结点
tmpHead.next = head;
ListNode prev = tmpHead;
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
prev.next = cur.next;
} else {
prev = cur;
}
cur = cur.next;
}
return tmpHead.next;
}
}