翻转单向链表和双向链表

  这种基础题目,细节问题上很容易出现问题,需要精神高度集中,做到一遍代码敲出来直接运行没有任何问题。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

class Node {
    public int val;
    public Node next;
    public Node(int val) {
        this.val = val;
    }
}

class Node2 {
    public int val;
    public Node2 pre;
    public Node2 next;
    public Node2(int val) {
        this.val = val;
    }
}

public class Main {
    public static Node reverseList(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
        Node pre = null;
        Node next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
    public static Node2 reverseDoubleList(Node2 head) {
        if (head == null || head.next == null) {
            return head;
        }
        Node2 pre = null;
        Node2 cur = null;
        while (head != null) {
            cur = head.next;
            head.next = pre;
            head.pre = cur;
            pre = head;
            head = cur;
        }
        return pre;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));


        int len1 = Integer.parseInt(bf.readLine());
        String[] elements1 = bf.readLine().split(" ");
        Node head1 = new Node(Integer.parseInt(elements1[0]));
        Node node1 = head1;
        for (int i = 1; i < len1; i++) {
            node1.next = new Node(Integer.parseInt(elements1[i]));
            node1 = node1.next;
        }
        Node res1 = reverseList(head1);
        while (res1 != null) {
            System.out.print(res1.val + " ");
            res1 = res1.next;
        }

        System.out.println();
        
        int len = Integer.parseInt(bf.readLine());
        String[] elements = bf.readLine().split(" ");
        Node2 head = new Node2(Integer.parseInt(elements[0]));
        Node2 Node2 = head;
        Node2 pre = null;
        for (int i = 1; i < len; i++) {
            Node2.next = new Node2(Integer.parseInt(elements[i]));
            Node2.pre = pre;
            Node2 = Node2.next;
            pre = Node2.pre;
        }
        Node2 res = reverseDoubleList(head);
        while (res != null) {
            System.out.print(res.val + " ");
            res = res.next;
        }
    }
}

你可能感兴趣的:(算法与数据结构)