您的位置:首页 > 其它

题目:删除排序链表中的重复元素

2015-08-19 18:57 399 查看

给定一个排序链表,删除所有重复的元素每个元素只留下一个。

您在真实的面试中是否遇到过这个题?

Yes

哪家公司问你的这个题?
Airbnb
Alibaba
Amazon Apple
Baidu Bloomberg
Cisco Dropbox
Ebay Facebook
Google Hulu
Intel Linkedin
Microsoft NetEase
Nvidia Oracle
Pinterest Snapchat
Tencent Twitter
Uber Xiaomi
Yahoo Yelp
Zenefits
感谢您的反馈

样例

给出1->1->2->null,返回
1->2->null


给出1->1->2->3->3->null,返回 1->2->3->null

标签 Expand

链表

思想:将链表转换成数组,剔除一样的数据,再生成链表
/**

* Definition for ListNode

* public class ListNode {

* int val;

* ListNode next;

* ListNode(int x) {

* val = x;

* next = null;

* }

* }

*/

public class Solution {

/**

* @param ListNode head is the head of the linked list

* @return: ListNode head of linked list

*/

public static ListNode deleteDuplicates(ListNode head) {

// write your code here

if(head == null) return null;

int count = 0;

ListNode x = head;

while(x!=null){

count++;

x = x.next;

}

int[] listArr = new int[count];

int f = 0;

ListNode y = head;

while(y!=null){

listArr[f++] = y.val;

y = y.next;

}

int k = 0;

for(int i=0;i<listArr.length;i++){

int j = 0;

while(j<k){

if(listArr[i]==listArr[j]){

break;

}

j++;

}

if(j==k){

listArr[k++] = listArr[i];

}

}

int[] resArr = new int[k];

for(int m=0;m<k;m++){

resArr[m] = listArr[m];

}

ListNode reNode = new ListNode(resArr[0]);

ListNode z = reNode;

for(int i=1;i<k;i++){

z.next = new ListNode(resArr[i]);

z = z.next ;

}

z.next = null;

return reNode;

}

}

另一种AC代码
分析:由于有序,所以p结点是否重复只需要和它的前一节点比较是否相等就可以了,我们可以定义一个helper新头结点链表

将p结点与新链表的尾结点比较,若不相等则加入新链表中。

/**

* Definition for ListNode

* public class ListNode {

* int val;

* ListNode next;

* ListNode(int x) {

* val = x;

* next = null;

* }

* }

*/

public class Solution {

/**

* @param ListNode head is the head of the linked list

* @return: ListNode head of linked list

*/

public static ListNode deleteDuplicates(ListNode head) {

// write your code here

if(head == null) return null;

ListNode res = new ListNode(head.val);

ListNode f = res ;

ListNode x = head.next;

while(x.next!=null){

if(x.val != f.val){

f.next = x;

f = f.next;

}

x=x.next;

}

if(x.val!=f.val){

f.next = x;

}else{

f.next = null;

}

return res;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: