3 Star 61 Fork 5

programmercarl / kamacoder-solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
0020.删除重复元素.md 9.36 KB
一键复制 编辑 原始数据 按行查看 历史

20. 删除重复元素

题目链接

C++

#include<iostream>
using namespace std;
// 定义链表节点结构体
struct LinkedNode {
    int val;
    LinkedNode* next;
    LinkedNode(int val):val(val), next(nullptr){}
};

void printLinkedList(LinkedNode* head) {
    LinkedNode* cur = head;
    while (cur != nullptr) {
        cout << cur->val << " ";
        cur = cur->next;
    }
    cout << endl;
}

// 过滤掉重复元素输出
void printLinkedListV(LinkedNode* head) {
    LinkedNode* cur = head;
    int lastA, lastB;
    while (cur != nullptr && cur->next != nullptr) { 
        if (cur->val != cur->next->val) cout << cur->val << " ";
        cur = cur->next;
    }
    cout << cur->val << " ";
    cout << endl;
}

int main() {

        int n, m;
        LinkedNode* dummyHead =  new LinkedNode(0); // 这里定义的头结点 是一个虚拟头结点,而不是真正的链表头结点
        while (cin >> n) {
            if (n == 0) {
                cout << "list is empty" << endl;
                continue;
            }
            LinkedNode* cur = dummyHead;
            while (n--) {
                cin >> m;
                LinkedNode* newNode = new LinkedNode(m);
                cur->next = newNode;
                cur = cur->next;
            }
            printLinkedList(dummyHead->next);
            printLinkedListV(dummyHead->next);
        }
}

Java

import java.util.Scanner;
 
public class Main{
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String[] str = sc.nextLine().split(" ");
            if (str[0].equals("0")) {
                System.out.println("list is empty");
            }
            ListNode dummyhead = new ListNode(-1);
            ListNode cur = dummyhead;
            //构造链表
            for (int i = 1; i < str.length; i++) {
                ListNode temp = new ListNode(Integer.parseInt(str[i]));
                cur.next = temp;
                cur = cur.next;
                if (i == str.length - 1) cur.next = null;
            }
            //输出原始链表
            ListNode pointer01 = dummyhead.next;
            while (pointer01 != null) {
                System.out.print(pointer01.val + " ");
                pointer01 = pointer01.next;
            }
            System.out.println();
            //删除重复节点
            ListNode fast = dummyhead.next;
            ListNode slow = dummyhead;
            while (fast != null) {
                if (fast.val == slow.val) {
                    slow.next = fast.next;
                    fast = fast.next;
                }
                else {
                    fast = fast.next;
                    slow = slow.next;
                }
            }
            //输出新链表
            ListNode pointer02 = dummyhead.next;
            while (pointer02 != null) {
                System.out.print(pointer02.val + " ");
                pointer02 = pointer02.next;
            }
            System.out.println();
        }
    }
}
 
class ListNode{
    public int val;
    public ListNode next;
    public ListNode(int val) {
        this.val = val;
    }
}
// 方法二:逻辑删除,即不打印重复元素即可
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {
            int N = sc.nextInt();
            if (N == 0) {
                System.out.println("list is empty");
                continue;
            }
            ListNode dummyHead = new ListNode(-1);
            ListNode cur = dummyHead;
            for (int i = 0; i < N; i++) {
                cur.next = new ListNode(sc.nextInt());
                cur = cur.next;
            }
            printOriginList(dummyHead.next);
            printListWithNoDup(dummyHead.next);
        }
        sc.close();

    }

    /* 输出原始链表 */
    private static void printOriginList(ListNode head) {
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }

    /* 输出没有重复元素的链表 */
    private static void printListWithNoDup(ListNode head) {
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            if (cur.val != cur.next.val)
                System.out.print(cur.val + " ");
            cur = cur.next;
        }
        // 处理最后一个元素和换行符
        System.out.print(cur.val + " \n");
    }

    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

}

python

class Node:
    def __init__(self, val):
        self.val = val
        self.next = None
 
def create_linked_list(nums):
    if not nums:
        return None
    head = Node(nums[0])
    cur = head
    for num in nums[1:]:
        cur.next = Node(num)
        cur = cur.next
    return head
 
def print_linked_list(head):
    if not head:
        print('list is empty')
        return
    cur = head
    while cur:
        print(cur.val, end=' ')
        cur = cur.next
    print()
 
def remove_duplicates(head):
    if not head:
        return None
    cur = head
    while cur and cur.next:
        if cur.val == cur.next.val:
            cur.next = cur.next.next
        else:
            cur = cur.next
    return head
 
while True:
    try:
        line = input().strip()
        if not line:
            break
        nums = list(map(int, line.split()))
        n = nums[0]
        nums = nums[1:]
        if n == 0:
            print('list is empty')
            continue
        head = create_linked_list(nums)
        print_linked_list(head)
        head = remove_duplicates(head)
        print_linked_list(head)
    except EOFError:
        break

Go

package main

import (
	"fmt"
)

func main() {
	for {
		var n int
		_, err := fmt.Scan(&n)
		if err != nil {
			return
		}
		if n == 0 {
			fmt.Println("list is empty")
			continue
		}

		dummyHead := &Node{}
		cur := dummyHead
		for n > 0 {
			var val int
			_, err = fmt.Scan(&val)
			if err != nil {
				return
			}
			node := &Node{val: val}
			cur.next = node
			cur = cur.next
			n--
		}
		show(dummyHead.next)
		show(removeDuplicates(dummyHead.next))
	}

}

func removeDuplicates(head *Node) *Node {
	if head == nil {
		return nil
	}
	cur := head
	pre := head
	for cur.next != nil {
		if pre.val == cur.next.val {
			cur.next = cur.next.next
		} else {
			cur = cur.next
			pre = pre.next
		}
	}
	return head
}

func show(head *Node) {
	if head == nil {
		return
	}
	cur := head
	for {
		fmt.Printf("%d ", cur.val)
		cur = cur.next
		if cur == nil {
			fmt.Println()
			return
		}
	}
}

type Node struct {
	val  int
	next *Node
}

Js

class ListNode {
    constructor(value){
         this.val = value;
         this.next = null;
    }
}

const readline = require('readline');

const rl = readline.createInterface({
    input:process.stdin,
    output:process.stdout,
})

rl.on('line',(line)=>{
    let num = line.split(' ').map(Number);
    let n = num[0];
    if(n === 0){
     console.log('list is empty');
     return;
    }
    
    let head = new ListNode(0);
    let current = head;
    for(let i = 1;i<=n;i++){
     current.next = new ListNode(num[i]);
     current = current.next;
    }
     
    current = head.next;
    let res = [];
    while (current !== null) {
        res.push(current.val);
        current = current.next;
    }
    console.log(res.join(' '));
      
      
    current = head.next;
    res = [];
    res.push(current.val)
    while(current && current.next){
        if(current.val == current.next.val){
            current.next = current.next.next;
        }else{
            current = current.next;
            res.push(current.val);
        }
    }
    console.log(res.join(' '));
        
})

C

#include <stdio.h>
#include <stdlib.h>

// 定义链表节点结构体
struct LinkedNode {
    int val;
    struct LinkedNode* next;
};

void printLinkedList(struct LinkedNode* head) {
    struct LinkedNode* cur = head;
    while (cur != NULL) {
        printf("%d ", cur->val);
        cur = cur->next;
    }
    printf("\n");
}

// 过滤掉重复元素输出
void printLinkedListV(struct LinkedNode* head) {
    struct LinkedNode* cur = head;
    while (cur != NULL && cur->next != NULL) {
        if (cur->val != cur->next->val) printf("%d ", cur->val);
        cur = cur->next;
    }
    printf("%d ", cur->val);
    printf("\n");
}

int main() {
    int n, m;

    // 这里定义的头结点是一个虚拟头结点,而不是真正的链表头结点
    struct LinkedNode* dummyHead = (struct LinkedNode*)malloc(sizeof(struct LinkedNode)); 
    dummyHead->next = NULL;

    while (scanf("%d", &n) == 1) {
        if (n == 0) {
            printf("list is empty\n");
            continue;
        }
        struct LinkedNode* cur = dummyHead;
        while (n--) {
            scanf("%d", &m);
            struct LinkedNode* newNode = (struct LinkedNode*)malloc(sizeof(struct LinkedNode));
            newNode->val = m;
            newNode->next = NULL;
            cur->next = newNode;
            cur = cur->next;
        }
        printLinkedList(dummyHead->next);
        printLinkedListV(dummyHead->next);
    }

    return 0;
}
1
https://gitee.com/programmercarl/kamacoder-solutions.git
git@gitee.com:programmercarl/kamacoder-solutions.git
programmercarl
kamacoder-solutions
kamacoder-solutions
main

搜索帮助