您的位置:首页 > 编程语言 > Java开发

Leetcode刷题记——83. Remove Duplicates from Sorted List(删除有序链表的重复结点)

2017-02-28 15:06 369 查看
一、题目叙述:

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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java
相关文章推荐