题目
题目链接:
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef
这题有一次面试某团的第一道题
思考
链表的基本操作
参考答案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
package mainimport . "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 := pHeadfor cur != nil {_, ok := cnt[cur.Val]if !ok {cnt[cur.Val] = 0}cnt[cur.Val] = cnt[cur.Val] + 1cur = cur.Next}newNode := &ListNode{-1, nil}tmp := newNodecur = pHeadfor cur != nil {k := cur.Valnext := cur.Nextif cnt[k] == 1 {cur.Next = niltmp.Next = curtmp = cur}cur = next}return newNode.Next
}
参考答案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;
}