剑指offer五十六之删除链表中重复的结点

一、题目

  在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

二、思路

  详见代码

三、代码

import java.util.ArrayList;

public class Solution {
    public ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null) {
            return null;
        }

        ArrayList<String> list = new ArrayList<>();
        String tmp = "";

        //删除数据相同的结点
        while (pHead != null) {
            if (list.contains(pHead.val + "")) {
                list.remove(pHead.val + "");
                tmp = pHead.val + "";
            } else if (!tmp.equals(pHead.val + "")) {
                list.add(pHead.val + "");
            }
            
            pHead = pHead.next;
        }

        ListNode head = null;
        ListNode curNode = null;
     

        for (int i = 0; i < list.size(); i++) {
            if (head == null) {
                //创建头结点
                head = new ListNode(Integer.parseInt(list.get(i)));
                curNode = head;
            } else {
                //添加结点
               curNode.next =new ListNode(Integer.parseInt(list.get(i)));
               curNode =curNode.next;
            }
        }

        return head;
    }
}
View Code

---------------------------------------------

参考链接:

https://www.nowcoder.com/questionTerminal/fc533c45b73a41b0b44ccba763f866ef

posted @ 2017-10-20 18:33  AI菌  阅读(193)  评论(0编辑  收藏  举报