题目
题目链接:
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef
这题有一次面试某团的第一道题
思考
链表的基本操作
参考答案Java
java
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
//map统计重复节点
Map<Integer, Integer> cnt = new HashMap<>();
ListNode cur = pHead;
while (cur != null) {
int k = cur.val;
if (!cnt.containsKey(k))
cnt.put(k, 0);
cnt.put(k, cnt.get(k) + 1);
cur = cur.next;
}
ListNode newNode = new ListNode(-1);
ListNode tmp = newNode;
cur = pHead;
while (cur != null) {
int k = cur.val;
ListNode next = cur.next;
if (cnt.get(k) == 1) {
cur.next = null;
tmp.next = cur;
tmp = cur;
}
cur = next;
}
return newNode.next;
}
}
参考答案Go
go
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param pHead ListNode类
* @return ListNode类
*/
func deleteDuplication(pHead *ListNode) *ListNode {
//map统计节点
cnt := map[int]int{}
cur := pHead
for cur != nil {
_, ok := cnt[cur.Val]
if !ok {
cnt[cur.Val] = 0
}
cnt[cur.Val] = cnt[cur.Val] + 1
cur = cur.Next
}
newNode := &ListNode{-1, nil}
tmp := newNode
cur = pHead
for cur != nil {
k := cur.Val
next := cur.Next
if cnt[k] == 1 {
cur.Next = nil
tmp.Next = cur
tmp = cur
}
cur = next
}
return newNode.Next
}
参考答案PHP
php
<?php
/*class ListNode{
var $val;
var $next = NULL;
function __construct($x){
$this->val = $x;
}
}*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param pHead ListNode类
* @return ListNode类
*/
function deleteDuplication( $pHead )
{
//map统计次数
$cnt = array();
$cur =$pHead;
while ($cur!=null){
$k = $cur->val;
if(!isset($cnt[$k])){
$cnt[$k] = 0;
}
$cnt[$k]+=1;
$cur = $cur->next;
}
$newNode = new ListNode(-1);
$tmp = $newNode;
$cur = $pHead;
while ($cur!=null){
$k = $cur->val;
$next = $cur->next;
if($cnt[$k] ==1){
$cur->next = null;
$tmp->next = $cur;
$tmp=$cur;
}
$cur = $next;
}
return $newNode->next;
}