Java remove duplicates from linked list

后端 未结 5 1690
眼角桃花
眼角桃花 2021-01-27 14:20

I want to remove duplicates from sorted linked list {0 1 2 2 3 3 4 5}.

`

public Node removeDuplicates(Node header)
{
    Node tempHeader = null;
    if(         


        
5条回答
  •  自闭症患者
    2021-01-27 14:55

    The loop is sorted, so you know that duplicates are going to sit next to each other. If you want to edit the list in place then, you've got to have two list pointers (which you do). The one you call tempHeader and prev, and you've got to advance them both in the the list as you go (which I don't see in the code). Otherwise, if you don't advance the prev pointer as you go, then you're always comparing the element under tempHeader to the first item in the list, which is not correct.

    An easier way to do this, however, is to build a new list as you go. Simply remember the value of the last item that you appended to the list. Then if the one that you're about to insert is the same then simply don't insert it, and when you're done, just return your new list.

提交回复
热议问题