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
.
看到这道题的第一反应就是很简单啊,就是删除重复元素,而且链表又是一个排好序的,就两个指针,一个观望,一个向下走
下面附上我的代码:
public ListNode deleteDuplicates(ListNode head) { if(head==null||head.next==null){ return head; } ListNode pNode = head; ListNode nNode = head.next; while(nNode!=null){ if(pNode.val==nNode.val){ pNode.next = nNode.next; nNode = nNode.next; } else{ pNode = nNode; nNode = nNode.next; } } return head; }
另附上我同学的一种做法: