Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
Given
1->1->2
, return 1->2
.Given
1->1->2->3->3
, return 1->2->3
.
比较简单的链表操作题,使用双指针的方法,一个扫描,一个保持当前没有重复的链表的结尾。
public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null) { return head; } ListNode temp1 = head, temp2 = head.next; while(temp1 != null) { while(temp2 != null && temp1.val == temp2.val) { temp2 = temp2.next; } temp1.next = temp2; temp1 = temp2; if(temp2 != null) temp2 = temp2.next; } return head; }
没有评论:
发表评论