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
.
题意:删除链表中重复的元素值,保留一个。
思路:双指针,首先判断链表是否为空或者只包含一个元素,如果是则返回头指针head,否则定义双指针p和q,p初始化指向head.next,q指向head,然后遍历链表,判断p和q所指向节点元素值是否相同,相同的话删除,不相同的话分别指向下一个结点。
代码:
public ListNode deleteDuplicates(ListNode head) { if (head==null||head.next==null) return head; ListNode p = head.next; ListNode q = head; while(p!=null){ if(p.val==q.val){ p=p.next; q.next=q.next.next; }else{ p=p.next; q=q.next; } } return head; }