Remove Duplicates from Sorted List


描述
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 static ListNode deleteDuplicates(ListNode head) {
 2         if (head == null || head.next == null) {
 3             return head;
 4         }
 5         ListNode ptr1 = head;
 6         ListNode ptr2 = head.next;
 7         while (ptr2 != null) {
 8             if (ptr1.data == ptr2.data) {
 9                 ptr2 = ptr2.next;
10                 if (ptr2 == null)
11                     ptr1.next = null;
12             } else {
13                 ptr1.next = ptr2;// 衔接链表
14                 ptr1 = ptr1.next;// 各移到下一个节点
15                 ptr2 = ptr2.next;
16             }
17         }
18         return head;
19     }

 

posted @ 2018-07-11 22:46  昵称真难想  阅读(125)  评论(0编辑  收藏  举报