一、题目叙述:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Subscribe to see which companies asked this question.
二、解题思路:
Easy题,删除有序链表里的重复结点,因为链表本身有序所以很简单。
思路:
(1)创建一个指针指向头结点,查看其后一结点是否与其值相等,若相等,删掉其后结点,否则,移动指针向后遍历。
(2)注意头结点为空的情况。
三、源码:
public class Solution
{
public ListNode deleteDuplicates(ListNode head)
{
ListNode tem = head;
if (head == null) return head;
while (tem.next != null)
{
if (tem.next.val == tem.val)
tem.next = tem.next.next;
else
tem = tem.next;
}
return head;
}
public static void main(String args[])
{
ListNode a = new ListNode(1);
ListNode first = a;
a.next = new ListNode(1);
a = a.next;
a.next = new ListNode(2);
//String a = "";
//String b = "";
// int[] digits = {0};
Solution solution = new Solution();
// int[][] abc = {{2}};
// int[] b = {2,3,4};
// for(int i = 0; i < abc.length; i ++)
ListNode res = solution.deleteDuplicates(first);
while (res != null)
{
System.out.print(res.val);
res = res.next;
}
}
}