算法设计：如何从已排序的链表中删除重复项？

2021年3月19日18:24:48 发表评论 359 次浏览

C ++

``````/* C++ Program to remove duplicates from a sorted linked list */
#include <bits/stdc++.h>
using namespace std;

class Node
{
public :
int data;
Node* next;
};

/* The function removes duplicates from a sorted list */
{
/* Pointer to traverse the linked list */

/* Pointer to store the next pointer of a node to be deleted*/
Node* next_next;

/* do nothing if the list is empty */
if (current == NULL)
return ;

/* Traverse the list till last node */
while (current->next != NULL)
{
/* Compare current node with next node */
if (current->data == current->next->data)
{
/* The sequence of steps is important*/
next_next = current->next->next;
free (current->next);
current->next = next_next;
}
else /* This is tricky: only advance if no deletion */
{
current = current->next;
}
}
}

/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
{
/* allocate node */
Node* new_node = new Node();

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

/* Function to print nodes in a given linked list */
void printList(Node *node)
{
while (node!=NULL)
{
cout<< " " <<node->data;
node = node->next;
}
}

/* Driver program to test above functions*/
int main()
{

/* Let us create a sorted linked list to test the functions
Created linked list will be 11->11->11->13->13->20 */

cout<< "Linked list before duplicate removal " ;

/* Remove duplicates from linked list */

cout<< "\nLinked list after duplicate removal " ;

return 0;
}

// This code is contributed by rathbhupendra``````

C

``````/* C Program to remove duplicates from a sorted linked list */
#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node* next;
};

/* The function removes duplicates from a sorted list */
{
/* Pointer to traverse the linked list */

/* Pointer to store the next pointer of a node to be deleted*/
struct Node* next_next;

/* do nothing if the list is empty */
if (current == NULL)
return ;

/* Traverse the list till last node */
while (current->next != NULL)
{
/* Compare current node with next node */
if (current->data == current->next->data)
{
/* The sequence of steps is important*/
next_next = current->next->next;
free (current->next);
current->next = next_next;
}
else /* This is tricky: only advance if no deletion */
{
current = current->next;
}
}
}

/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push( struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
( struct Node*) malloc ( sizeof ( struct Node));

/* put in the data  */
new_node->data  = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

/* Function to print nodes in a given linked list */
void printList( struct Node *node)
{
while (node!=NULL)
{
printf ( "%d " , node->data);
node = node->next;
}
}

/* Driver program to test above functions*/
int main()
{

/* Let us create a sorted linked list to test the functions
Created linked list will be 11->11->11->13->13->20 */

printf ( "\n Linked list before duplicate removal  " );

/* Remove duplicates from linked list */

printf ( "\n Linked list after duplicate removal " );

return 0;
}``````

Java

``````// Java program to remove duplicates from a sorted linked list
{

class Node
{
int data;
Node next;
Node( int d) {data = d; next = null ; }
}

void removeDuplicates()
{

/* Traverse list till the last node */
while (curr != null ) {
Node temp = curr;
/*Compare current node with the next node and
keep on deleting them until it matches the current
node data */
while (temp!= null && temp.data==curr.data) {
temp = temp.next;
}
/*Set current node next to the next different
element denoted by temp*/
curr.next = temp;
curr = curr.next;
}
}

/* Utility functions */

/* Inserts a new Node at front of the list. */
public void push( int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);

/* 3. Make next of new Node as head */

/* 4. Move the head to point to new Node */
}

/* Function to print linked list */
void printList()
{
while (temp != null )
{
System.out.print(temp.data+ " " );
temp = temp.next;
}
System.out.println();
}

/* Driver program to test above functions */
public static void main(String args[])
{
llist.push( 20 );
llist.push( 13 );
llist.push( 13 );
llist.push( 11 );
llist.push( 11 );
llist.push( 11 );

System.out.println( "List before removal of duplicates" );
llist.printList();

llist.removeDuplicates();

System.out.println( "List after removal of elements" );
llist.printList();
}
}
/* This code is contributed by Rajat Mishra */``````

Python 3

``````# Python3 program to remove duplicate
# nodes from a sorted linked list

# Node class
class Node:

# Constructor to initialize
# the node object
def __init__( self , data):
self .data = data
self . next = None

def __init__( self ):

# Function to insert a new node
# at the beginning
def push( self , new_data):
new_node = Node(new_data)

# Given a reference to the head of a
# list and a key, delete the first
# occurence of key in linked list
def deleteNode( self , key):

# If head node itself holds the
# key to be deleted
if (temp is not None ):
if (temp.data = = key):
temp = None
return

# Search for the key to be deleted, # keep track of the previous node as
# we need to change 'prev.next'
while (temp is not None ):
if temp.data = = key:
break
prev = temp
temp = temp. next

# if key was not present in
if (temp = = None ):
return

prev. next = temp. next

temp = None

# Utility function to print the
def printList( self ):
while (temp):
print (temp.data , end = ' ' )
temp = temp. next

# This function removes duplicates
# from a sorted list
def removeDuplicates( self ):
if temp is None :
return
while temp. next is not None :
if temp.data = = temp. next .data:
new = temp. next . next
temp. next = None
temp. next = new
else :
temp = temp. next

# Driver Code

llist.push( 20 )
llist.push( 13 )
llist.push( 13 )
llist.push( 11 )
llist.push( 11 )
llist.push( 11 )
print ( "Created Linked List: " )
llist.printList()
print ()
print ( "Linked List after removing" , "duplicate elements:" )
llist.removeDuplicates()
llist.printList()

# This code is contributed by
# Dushyant Pathak.``````

C#

``````// C# program to remove duplicates
// from a sorted linked list
using System;

{

class Node
{
public int data;
public Node next;
public Node( int d)
{
data = d; next = null ;
}
}

void removeDuplicates()
{

/* Pointer to store the next
pointer of a node to be deleted*/
Node next_next;

/* do nothing if the list is empty */
return ;

/* Traverse list till the last node */
while (current.next != null )
{

/*Compare current node with the next node */
if (current.data == current.next.data)
{
next_next = current.next.next;
current.next = null ;
current.next = next_next;
}
else // advance if no deletion
current = current.next;
}
}

/* Utility functions */

/* Inserts a new Node at front of the list. */
public void push( int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);

/* 3. Make next of new Node as head */

/* 4. Move the head to point to new Node */
}

/* Function to print linked list */
void printList()
{
while (temp != null )
{
Console.Write(temp.data+ " " );
temp = temp.next;
}
Console.WriteLine();
}

/* Driver code */
public static void Main(String []args)
{
llist.push(20);
llist.push(13);
llist.push(13);
llist.push(11);
llist.push(11);
llist.push(11);

Console.WriteLine( "List before removal of duplicates" );
llist.printList();

llist.removeDuplicates();

Console.WriteLine( "List after removal of elements" );
llist.printList();
}
}

/* This code is contributed by 29AjayKumar */``````

``````Linked list before duplicate removal  11 11 11 13 13 20
Linked list after duplicate removal  11 13 20``````

C ++

``````/* C++ Program to remove duplicates
from a sorted linked list */
#include <bits/stdc++.h>
using namespace std;

class Node
{
public :
int data;
Node* next;
};

/* The function removes duplicates
from a sorted list */
{
/* Pointer to store the pointer of a node to be deleted*/
Node* to_free;

/* do nothing if the list is empty */
return ;

/* Traverse the list till last node */
{

/* Compare head node with next node */
{
/* The sequence of steps is important.
to_free pointer stores the next of head
pointer which is to be deleted.*/
free (to_free);
}
else /* This is tricky: only
{
}
}
}

/* UTILITY FUNCTIONS */
/* Function to insert a node at the
beginging of the linked list */
{
/* allocate node */
Node* new_node = new Node();

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

/* Function to print nodes
in a given linked list */
void printList(Node *node)
{
while (node!=NULL)
{
cout<< " " <<node->data;
node = node->next;
}
}

/* Driver code*/
int main()
{

/* Let us create a sorted linked
list to test the functions
11->11->11->13->13->20 */

cout<< "Linked list before duplicate removal " ;

/* Remove duplicates from linked list */

cout<< "\nLinked list after duplicate removal " ;

return 0;
}
// This code is contributed by Ashita Gupta``````

C

``````/* C recursive Program to remove duplicates from a sorted linked list */
#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node* next;
};
/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the linked list */
void push( struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
( struct Node*) malloc ( sizeof ( struct Node));

/* put in the data  */
new_node->data  = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

/* Function to print nodes in a given linked list */
void printList( struct Node *node)
{
while (node!=NULL)
{
printf ( "%d " , node->data);
node = node->next;
}
}

if (head == nullptr) return nullptr;

Node *tmp;
// If find next element duplicate, preserve the next pointer to be deleted, // skip it, and then delete the stored one. Return head
free (tmp);
}

else {

// if doesn't find next element duplicate, leave head
// and check from next element
}
}

int main()
{

/* Let us create a sorted linked list to test the functions
Created linked list will be 11->11->11->13->13->20 */

printf ( "\n Linked list before duplicate removal  " );

/* Remove duplicates from linked list */

printf ( "\n Linked list after duplicate removal " );

return 0;
}
/* This code is contributed by Yogesh shukla */``````

Java

``````// Java Program to remove duplicates
// from a sorted linked list
class GFG
{
static class Node
{
int data;
Node next;
};

// The function removes duplicates
// from a sorted list
{
/* Pointer to store the pointer
of a node to be deleted*/
Node to_free;

/* do nothing if the list is empty */
return null ;

/* Traverse the list till last node */
{

/* Compare head node with next node */
{
/* The sequence of steps is important.
to_free pointer stores the next of head
pointer which is to be deleted.*/
}

/* This is tricky: only advance if no deletion */
else
{
}
}
}

/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging
static Node push(Node head_ref, int new_data)
{
/* allocate node */
Node new_node = new Node();

/* put in the data */
new_node.data = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

/* Function to print nodes in a given linked list */
static void printList(Node node)
{
while (node != null )
{
System.out.print( " " + node.data);
node = node.next;
}
}

/* Driver code*/
public static void main(String args[])
{

/* Let us create a sorted linked list
to test the functions
Created linked list will be 11.11.11.13.13.20 */

" duplicate removal " );

/* Remove duplicates from linked list */

" duplicate removal " );
}
}

// This code is contributed by Arnab Kundu``````

Python3

``````# Python3 Program to remove duplicates
# from a sorted linked list
import math

class Node:
def __init__( self , data):
self .data = data
self . next = None

# The function removes duplicates
# from a sorted list

# Pointer to store the pointer of a node
# to be deleted to_free

# do nothing if the list is empty
if (head = = None ):
return

# Traverse the list till last node
if (head. next ! = None ):

# Compare head node with next node

# The sequence of steps is important.
# to_free pointer stores the next of head
# pointer which is to be deleted.

# free(to_free)

# This is tricky: only advance if no deletion
else :

# UTILITY FUNCTIONS
# Function to insert a node at the
# beginging of the linked list

# allocate node
new_node = Node(new_data)

# put in the data
new_node.data = new_data

# link the old list off the new node

# move the head to point to the new node

# Function to print nodes in a given linked list
def printList(node):
while (node ! = None ):
print (node.data, end = " " )
node = node. next

# Driver code
if __name__ = = '__main__' :

# Let us create a sorted linked list
# to test the functions
# Created linked list will be 11.11.11.13.13.20

print ( "Linked list before duplicate removal " , end = "")

# Remove duplicates from linked list

print ( "\nLinked list after duplicate removal " , end = "")

# This code is contributed by Srathore``````

C#

``````// C# Program to remove duplicates
// from a sorted linked list
using System;

class GFG
{
public class Node
{
public int data;
public Node next;
};

// The function removes duplicates
// from a sorted list
{
/* Pointer to store the pointer
of a node to be deleted*/
Node to_free;

/* do nothing if the list is empty */
return null ;

/* Traverse the list till last node */
{

/* Compare head node with next node */
{
/* The sequence of steps is important.
to_free pointer stores the next of head
pointer which is to be deleted.*/
}

/* This is tricky: only advance if no deletion */
else
{
}
}
}

/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging
static Node push(Node head_ref, int new_data)
{
/* allocate node */
Node new_node = new Node();

/* put in the data */
new_node.data = new_data;

/* link the old list off the new node */

/* move the head to point to the new node */
}

/* Function to print nodes in
static void printList(Node node)
{
while (node != null )
{
Console.Write( " " + node.data);
node = node.next;
}
}

// Driver code
public static void Main(String []args)
{

/* Let us create a sorted linked list
to test the functions
Created linked list will be 11.11.11.13.13.20 */

" duplicate removal " );

/* Remove duplicates from linked list */

" duplicate removal " );
}
}

// This code is contributed by PrinciRaj1992``````

``````Linked list before duplicate removal  11 11 11 13 13 20
Linked list after duplicate removal  11 13 20``````

Java

``````// Java program to remove duplicates
// from a sorted linked list
{

class Node
{
int data;
Node next;
Node( int d) {
data = d;
next = null ;
}
}

// Function to remove duplicates
// from the given linked list
void removeDuplicates()
{
// temp will iterate to the
// prev will point towards
// the first occurence of every element

// Traverse list till the last node
while (temp != null ) {

// Compare values of both pointers
if (temp.data!=prev.data)
{
/* if the value of prev is
not equal to the value of
temp that means there are no
more occruences of the prev data.
So we can set the next of
prev to the temp node.*/
prev.next=temp;
prev=temp;
}
/*Set the temp to the next node*/
temp=temp.next;
}
/*This is the edge case if there
are more than one occurrences
of the last element*/
if (prev!=temp){
prev.next= null ;
}
}

/* Utility functions */

/* Inserts a new Node at front of the list. */
public void push( int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);

/* 3. Make next of new Node as head */

/* 4. Move the head to point to new Node */
}

/* Function to print linked list */
void printList()
{
while (temp != null )
{
System.out.print(temp.data+ " " );
temp = temp.next;
}
System.out.println();
}

/* Driver program to test above functions */
public static void main(String args[])
{
llist.push( 20 );
llist.push( 13 );
llist.push( 13 );
llist.push( 11 );
llist.push( 11 );
llist.push( 11 );

System.out.print( "List before " );
System.out.println( "removal of duplicates" );
llist.printList();

llist.removeDuplicates();

System.out.println( "List after removal of elements" );
llist.printList();
}
}
/* This code is contributed by Arshita */``````

``````List before removal of duplicates
11 11 11 13 13 20
List after removal of elements
11 13 20``````