/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode res=head;
if( head==null )
{
return res;
}
ListNode st=head;
while( st.next!=null )
{
boolean finish=false;
while( st.val==st.next.val )
{
st.next=st.next.next;
if( st.next==null )
{
finish=true;
break;
}
}
st=st.next;
if( finish==true)
{
break;
}
}
return res;
}
}
没什么难度的一道链表题。 由于链表是有序的,所以判断当前节点是否重复,和之前节点比较即可。 我们只需遍历链表一遍,将所有重复节点去除即可。 要注意的就是边界空节点,细心一点即可。