题目地址https://leetcode.com/problems/remove-duplicates-from-sorted-list/
83. Remove Duplicates from Sorted List(Easy)
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
solution
我的解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head){
ListNode p = head , t = head; //p指向当前结点,t指向去重后的尾结点
while (p != null && p.next != null)
{
while (p.next != null && p.val == p.next.val) //找到下一个结点值不重复的结点p.next
p = p.next;
if (p.next != null) //将p.next连在t后面
{
p = p.next;
t.next = p;
t = p;
}
else //如果p.next为null,说明去重已完成
t.next = null;
}
return head;
}
}
官方解法
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.next.val == current.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
reference
https://leetcode.com/problems/remove-duplicates-from-sorted-list/solution/
总结
题意是给定一个有序链表,要求删掉里面重复的元素。
- 我的思路是用while循环遍历链表,接着用一个while循环找到与当前结点值不同的下一个结点,然后将找到的结点与当前新链表的尾结点连接起来,直到外层while循环结束.
- 官方思路简单粗暴,直接比较当前结点与下一结点的值,如果相等,则将当前结点与下一结点的下一结点连接起来,否则继续检查下一结点.
Notes
1.这种题感觉没必要想的很复杂,我就是考虑复杂了,导致我的解法比官方解法慢.
2.链表的插入与删除要特别注意头结点与尾结点.