/** * 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 dummyHead=new ListNode(); dummyHead.next=head; ListNode prev=dummyHead; while(prev.next!=null){ if(prev.next.val==val){ prev.next=prev.next.next; }else{ prev=prev.next; } } return dummyHead.next; } }
递归:
head.val==val ; //return子函数返回值
否则 return head
/** * 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 null; } //删除所有值为val的节点后,子链表的头结点可能会发生变化 //如果子链表的头结点是val,那我就得换个头结点 //更新当前第二个结点的引用 head.next=removeElements(head.next,val); if(head.val==val){ return head.next; } return head; } }
最后If 优化写法
return head.val==val ? head.next :head;
prev=0,cur=1,
while (cur.val !=null){
cur.val==prev.val ---cur++;
cur.val !=prev.val -- prev.next=cur;prev++, cur++;
}
/** * 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 deleteDuplicates(ListNode head) { if(head==null||head.next==null){ return head ; } ListNode prev=head; ListNode cur=prev.next; while (cur !=null){ if(prev.val!=cur.val){ prev.next=cur; prev=prev.next; cur=cur.next; }else{ cur=cur.next; } } return head; } }
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(0, head);
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
if (cur.next.val == cur.next.next.val) {
int x = cur.next.val;
while (cur.next != null && cur.next.val == x) {
cur.next = cur.next.next;
}
} else {
cur = cur.next;
}
}
return dummy.next;
}
}
package leetCode;
/**
* 递归方法
*/
class Solution{
public ListNode deleteDuplicates(ListNode head){
if (head==null|| head.next==null){
return head;
}
head.next=deleteDuplicates(head.next);
if (head.val==head.next.val){
return head.next;
}else {
return head;
}
}
}
package leetCode;
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;
}
}
package leetCode;
public class num82 {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode prev = dummyHead;
ListNode cur = prev.next;
while (cur != null) {
ListNode next = cur.next;
if (next == null) {
break;
} else {
if (cur.val != next.val