Remove Duplicates from Sorted List
Description
Given a sorted linked list, delete all duplicates such that each element appear only once.
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: head is the head of the linked list
* @return: head of linked list
*/
public ListNode deleteDuplicates(ListNode head) {
// write your code here
if(head == null) {
return null ;
}
ListNode node = head ;
while(node.next != null){
if(node.val == node.next.val){
node.next = node.next.next ;
}else{
node = node.next ;
}
}
return head ;
}
}
本文介绍了一种从已排序链表中移除所有重复元素的方法,使得每个元素只出现一次。通过迭代检查相邻节点并调整指针,最终返回处理后的链表头部。
714

被折叠的 条评论
为什么被折叠?



