题解 | #牛群排列去重#
牛群排列去重
https://www.nowcoder.com/practice/8cabda340ac6461984ef9a1ad66915e4
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
if (head == null || head.next == null) {
return head;
}
ListNode current = head;
while (current != null && current.next != null) {
if (current.val == current.next.val) {
current.next = current.next.next; // Remove duplicate node
} else {
current = current.next;
}
}
return head;
}
}
题目考察的知识点包括链表基本操作(遍历、删除节点)、使用虚拟头节点简化链表操作、以及对链表节点值的比较和处理。
这个问题涉及到链表的操作和去重,可以按照以下步骤来解决:
- 定义一个指针,用于遍历链表。
- 使用一个临时变量记录当前不重复的牛的编号。
- 遍历链表,比较当前节点的值与临时变量的值是否相同:如果相同,说明出现重复,将当前节点从链表中移除。如果不同,更新临时变量的值为当前节点的值。
- 继续遍历链表直到末尾。


