Loading

83. 删除排序链表中的重复元素

83. 删除排序链表中的重复元素

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/description/

package com.test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Lesson083 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(3);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        printNode(l1);
        ListNode ll = deleteDuplicates(l1);
        printNode(ll);

    }
    public static ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode ll = head;
        int val = ll.val;
        while (ll.next != null) {
            int val1 = ll.next.val;
            // 找到相同的元素了
            if (val1 - val == 0) {
                // ll的next就换成下一个了;
                ll.next = ll.next.next;
            }else {
                val = val1;
                ll = ll.next;
            }
        }
        return head;
    }
    private static void printNode(ListNode l11) {
        System.out.print(l11.val);
        if(l11.next != null){
            System.out.print("->");
            printNode(l11.next);
        }else{
            System.out.println("");
        }
    }
}

 

posted @ 2018-08-26 21:29  stono  阅读(123)  评论(0编辑  收藏  举报