首页 > 其他 > 详细

[LeetCode]Remove Duplicates from Sorted List

时间:2017-05-07 18:24:15      阅读:221      评论:0      收藏:0      [点我收藏+]

题目:给定一个有序的链表。要求去除链表中反复项

算法:遍历链表。通过指针推断反复项,反复节点的删除仅仅须要改变next指向就可以

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
	    	if (null == head) {
	    		// empty list
	    		return null;
	    	}
	    	
	        ListNode ptr = head;
	        ListNode dupPtr = head.next;
	        while (null != dupPtr) {
	        	while (null!=dupPtr && ptr.val==dupPtr.val) {
	        		dupPtr = dupPtr.next;
	        	}
	        	if (null != dupPtr) {
	        		ptr.next = dupPtr;
	        		ptr = dupPtr;
	        		dupPtr = dupPtr.next;
	        	}
	        }
	        ptr.next = null;
	        
	        return head;
	    }
}


[LeetCode]Remove Duplicates from Sorted List

原文:http://www.cnblogs.com/ljbguanli/p/6821353.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!