难度:简单
频次:47
题目:给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
解题思路:就是双指针遍历,如果前后相同,删除一个,不相同就继续遍历
代码
/*** Definition for singly-linked list.* public class ListNode {*int val;*ListNode next;*ListNode() {}*ListNode(int val) { this.val = val; }*ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/class Solution {public ListNode deleteDuplicates(ListNode head) {ListNode pre=head,cur=head;if(head==null) return null;cur=head.next;while(cur!=null){if(pre.val==cur.val) {cur=cur.next;pre.next=cur;}else {cur=cur.next;pre=pre.next;}}return head;}}
可以改进:利用一个指针
/*** Definition for singly-linked list.* public class ListNode {*int val;*ListNode next;*ListNode() {}*ListNode(int val) { this.val = val; }*ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/class Solution {public ListNode deleteDuplicates(ListNode head) {ListNode cur=head;if(head==null) return null;while(cur!=null&&cur.next!=null){if(cur.val==cur.next.val) {cur.next=cur.next.next;}else {cur=cur.next;}}return head;}}
如果觉得《Leetcode 83. 删除排序链表中的重复元素》对你有帮助,请点赞、收藏,并留下你的观点哦!