Title description
Delete the duplicate elements in the given linked list so that all the elements in the linked list appear only once.
For example: the
given linked list is 1-> 1-> 2, and the returned 1-> 2. The
given linked list is 1-> 1- > 2-> 3-> 3, return 1-> 2-> 3.
analysis
- For example, 1 1 1 2 3 3, use the cur pointer to traverse the linked list. If the next node element is the same as this node element, delete the next node, and cur will not move. If the next node element is not the same as this node element, cur moves.
java code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null){return head;}
ListNode cur = head;
while(cur != null && cur.next != null){
if(cur.next.val == cur.val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}