LeetCode -- Remove Duplicates from Sorted List, leetcode
Given a sorted linked list, delete all duplicates such that each element appear onlyOnce.
For example,
Given1->1->2, Return1->2.
Given1->1->2->3->3, Return1->2->3.
The LeetCode is a simple question. when processing the linked list, only one repeated value is retained in the linked list. The general process is as follows:
1. First, judge whether the linked list is empty or there is only one node. If yes, return directly. Otherwise, perform general processing.
2. The head is the previous node, and the nextNode is the next node pointed to by the rear head. If the nextNode is not empty, it indicates that it does not reach the end of the linked list and enters the while loop.
3. Note that when head. val = nextNode. val is over two duplicate values, point the next node of the head to the next node of the nextNode, and remove the nextNode. The head node remains unchanged.
Head. val! = NextNode. val, head moves to nextNode.
Finally, assign nextNode to the next node to which next points, and continue the cyclic comparison.
/** * 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) { ListNode result = head; if(head==null||head.next==null) return head; else{ ListNode nextNode = head.next; while(nextNode!=null){ if(head.val == nextNode.val) head.next = nextNode.next; else head = nextNode; nextNode = head.next; } } return result; }}