1. 程式人生 > >劍指offer五十六之刪除鏈表中重復的結點

劍指offer五十六之刪除鏈表中重復的結點

string opened get spl size java nod ger 劍指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

劍指offer五十六之刪除鏈表中重復的結點