【编程】链表问题

来源:互联网 发布:钩尖江湖直销淘宝店 编辑:程序博客网 时间:2024/05/29 16:47

1。翻转单向链表
2。删除无序链表中值重复的节点

import java.util.HashSet;import java.util.Scanner;public class Node {    public int value;    public Node next;    public Node(int data) {        this.value = data;        next = null;    }    public Node() {        next = null;    }    //翻转链表    public static Node reverseList(Node head) {        Node pre = null;        Node next = null;        while(head != null) {            next = head.next;            head.next = pre;            pre = head;            head = next;        }        return pre;    }    /**     * 头插法创建链表,手动输入     */    public static Node createLinkedList() {        Node head = null;        Scanner scanner = new Scanner(System.in);        while(scanner.hasNext()) {            int reader = scanner.nextInt();            Node newNode = new Node(reader);            newNode.next = head;            head = newNode;        }        return head;    }    /*     * 遍历元素     */    public static void travelLinkedList(Node head) {        Node pnext = head;        while(pnext != null) {            System.out.print(pnext.value + "  ");            pnext = pnext.next;        }        System.out.println();    }    /*     * 删除无序链表中值重复的节点, 借助HashSet空间复杂度O(n),时间复杂度O(n)     */    public static void removeRepeatElementMethodOne(Node head) {        if(head == null) return;        else {            HashSet<Integer> set = new HashSet<Integer>();            Node pre = head;            Node curr = head.next;            set.add(head.value);            while(curr != null) {                if(set.contains(curr.value)) {                    pre.next = curr.next;                } else {                    set.add(curr.value);                    pre = curr;                }                curr = curr.next;            }        }    }    /*     * 除无序链表中值重复的节点,空间复杂度O(1)时间复杂度O(n^2)     */    public static void removeRepeatElementMethodTwo(Node head) {        Node cur = head;        Node pre = null;        Node next = null;        while(cur != null) {            pre = cur;            next = cur.next;            while(next != null) {                if(cur.value == next.value) {                    pre.next = next.next;                }else {                    pre = next;                }                next = next.next;            }            cur = cur.next;        }    }    //测试翻转单向链表    public static void testReverseList() {        Node head = createLinkedList();        //员链表顺序        travelLinkedList(head);        Node newHead = reverseList(head);        //翻转后链表顺序        travelLinkedList(newHead);    }    //测试删除无序链表中值重复的节点    public static void testRemoveRepeatElementOne() {        Node head = createLinkedList();        removeRepeatElementMethodTwo(head);        //removeRepeatElementMethodOne(head);        travelLinkedList(head);    }    public static void main(String[] args) {        //testReverseList();        testRemoveRepeatElementOne();    }}
原创粉丝点击