zoukankan      html  css  js  c++  java
  • LeetCode83----删除排序链表中的重复元素

    给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

    示例 1:

    输入: 1->1->2
    输出: 1->2
    

    示例 2:

    输入: 1->1->2->3->3
    输出: 1->2->3

    思路:
    (1)定义两个指针,cur1和cur2,初始时cur1指向head,cur2指向head.next
    (2)如果俩指针的值相等,就让cur1的next等于cur2的next,同时cur2指向next
    (3)如果俩指针不相等,cur1指向next,cur指向next
    (4)然后继续比较cur2和cur1的值

    代码如下:
    public class LeetCode83 {
    	public static class ListNode {
    		int val;
    		ListNode next;
    
    		ListNode(int x) {
    			val = x;
    		}
    	}
    
    	public ListNode deleteDuplicates(ListNode head) {
    		if (head == null || head.next == null) {
    			return head;
    		}
    		ListNode prev = head;
    		ListNode cur = head.next;
    		while (cur != null) {
    			if (prev.val == cur.val) {
    				prev.next = cur.next;
    			} else {
    				prev = prev.next;
    			}
    			cur = cur.next;
    		}
    		return head;
    	}
    }
    
    
    

      

     
  • 相关阅读:
    JDBC 精度
    AIX性能监控
    OID View
    Deci and Centi Seconds parsing in java
    SpringMVC @RequestBody问题:Unrecognized field , not marked as ignorable
    Linux SNMP oid
    MySQL 监控
    SVN 搭建
    C# 之 继承
    storm单词计数 本地运行
  • 原文地址:https://www.cnblogs.com/Booker808-java/p/9162254.html
Copyright © 2011-2022 走看看