您的位置:首页 > 其它

[LeetCode]Remove Duplicates from Sorted List

2014-07-02 20:20 274 查看
题目:给定一个有序的链表,要求去除链表中重复项

算法:遍历链表,通过指针判断重复项,重复节点的删除只需要改变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;
	    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: