原地删除有序链表中的重复节点
删除有序链表中重复出现的元素
http://www.nowcoder.com/questionTerminal/71cef9f8b5564579bf7ed93fbe0b2024
用哑节点 + 快慢指针
public class Solution { /** * * @param head ListNode类 * @return ListNode类 */ public ListNode deleteDuplicates (ListNode head) { // write code here if(head == null) return null; //定义哑节点 ListNode newNode = new ListNode(-1); newNode.next = head; //快慢指针 ListNode slow = newNode, fast = head; while(fast != null && fast.next != null){ //若前后值相等 if(fast.val == fast.next.val){ //就循环找到一个不相等的节点 ListNode temp = fast.next; while(temp != null && temp.val == fast.val){ temp = temp.next; } //慢指针的下一个是只出现过一次的 slow.next = temp; fast = temp; }else{ //不相等,则前进 slow = slow.next; fast = fast.next; } } return newNode.next; } }
注意此题是只保留出现一次的元素。
若只删除重复出现的元素,比如:
同样是用快慢指针,但不需要用到哑节点
class Solution { public ListNode deleteDuplicates(ListNode head) { //利用快慢指针 if(head == null) return null; ListNode slow = head; ListNode fast = head.next; while(fast != null){ if(slow.val != fast.val){ slow.next = fast; slow = slow.next; } fast = fast.next; } slow.next = null; return head; } }
字节算法题解 文章被收录于专栏
最近在刷字节的题库!! 春招给我冲!!!