83. Remove duplicate nodes from the sorted list remove duplicates from Sorted List

Source: Internet
Author: User


Given a sorted linked list, delete all duplicates such this each element appear only once.

For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

Remove duplicate nodes in a single linked list

  
 
  1. public class Solution {
  2. public ListNode DeleteDuplicates(ListNode head) {
  3. if (head == null)
  4. {
  5. return null;
  6. }
  7. ListNode node = head;
  8. ListNode nextNode = null;
  9. while (node.next != null)
  10. {
  11. if (node.val == node.next.val)
  12. {
  13. nextNode = node.next;
  14. while (nextNode.val == node.val)
  15. {
  16. if (nextNode.next == null)
  17. {
  18. node.next = null;
  19. return head;
  20. }
  21. else
  22. {
  23. nextNode = nextNode.next;
  24. }
  25. }
  26. node.next = nextNode;
  27. node = nextNode;
  28. }
  29. else
  30. {
  31. node = node.next;
  32. }
  33. }
  34. return head;
  35. }
  36. }


  
 
  1. public class Solution {
  2. if (head == null) return head;
  3. ListNode node = head;
  4. while (node.next != null)
  5. {
  6. if (node.val == node.next.val)
  7. {
  8. node.next = node.next.next;
  9. }
  10. else
  11. {
  12. node = node.next;
  13. }
  14. }
  15. return head;
  16. }
  17. }

The recursive version of Daniel

Https://discuss.leetcode.com/topic/14775/3-line-java-recursive-solution



From for notes (Wiz)

83. Remove duplicate nodes from the sorted list remove duplicates from Sorted List

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.