- 删除排序链表中的重复元素
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表
提示:
链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100
题目数据保证链表已经按升序排列
首先都要判断一下链表是否为空
思路1:因为是有序的链表,所以只需要比对相邻的元素是否相同,双指针进行比较
p->指向不重复的最后一个节点
q->进行遍历
若p->==q->则q->=q.next->
思路2:直接在链表上操作,如果相邻两个相同直接把指针指向下一个,不占用额外空间
方法一
public ListNode DeleteDuplicates(ListNode head)
{
if (head == null || head.next == null)
{
return head;
}
ListNode currentNode = head;
ListNode loopNode = head.next;
while (loopNode != null)
{
if (loopNode.val != currentNode.val)
{
currentNode.next = loopNode;
currentNode = loopNode;
}
loopNode = loopNode.next;
}
currentNode.next = null;
return head;
}
方法二
public class Solution {
public ListNode DeleteDuplicates(ListNode head) {
if (head == null || head.next == null)
{
return head;
}
var rememberTop = head;
var next = head.next;
while(head != null && next != null)
{
if(next.val == head.val)
{
next = next.next;
head.next = next;
}
else
{
head = head.next;
next = head.next;
}
}
return rememberTop;
}
}