码迷,mamicode.com
首页 > 编程语言 > 详细

83. 移除已排序链表中重复的节点 Remove Duplicates from Sorted List

时间:2017-01-14 12:53:22      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:public   san   mon   class   ext   tle   www   href   top   


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

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

移除单链表中重复的节点

  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. }

大牛的递归版本

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





83. 移除已排序链表中重复的节点 Remove Duplicates from Sorted List

标签:public   san   mon   class   ext   tle   www   href   top   

原文地址:http://www.cnblogs.com/xiejunzhao/p/cf812aceadb80e2c2282e44ea1ad7172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!