删除排序链表中的重复元素
func deleteDuplicates( head *ListNode ) *ListNode { new := &ListNode{Next:head} pre,cur := new,head for cur != nil{ for cur.Next != nil && cur.Val == cur.Next.Val{ cur = cur.Next } pre.Next = cur //删除中间重复节点 pre=cur //移动pre节点 cur = cur.Next //移动cur节点 } return new.Next }
https://leetcode.cn/problems/remove-duplicates-from-sorted-list-ii/
双指针法
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ //思路: //1、遍历当前节点cur,记录cur的前一个节点为pre //2、如果cur有重复节点,跳过 //3、通过pre和cur的前后关系判断,cur是否有重复关系,如果pre.Next==cur,则说明cur无重复 func deleteDuplicates(head *ListNode) *ListNode{ new := &ListNode{Next:head} pre,cur := new,head for cur != nil{ for cur.Next != nil && cur.Val == cur.Next.Val{ cur = cur.Next } if pre.Next == cur{//pre.Next == cur,说明cur.Val这个值没有重复的元素 pre = cur }else{ pre.Next = cur.Next//相当于删除中间重复的元素节点 } cur = cur.Next } return new.Next }
等风起的那一天,我已准备好一切