链表的创建、逆序、打印

1、链表节点类

public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
View Code

2、链表逆序类

public class ReverseList {
    public ListNode reverseList(ListNode head) {
        if(head==null)
            return null;
        //head为当前节点,如果当前节点为空的话,那就什么也不做,直接返回null;
        ListNode pre = null;
        ListNode next = null;
        //当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点
        //需要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2
        //即pre让节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了
        //所以需要用到pre和next两个节点
        //1->2->3->4->5
        //1<-2<-3 4->5
        while(head!=null){
            //做循环,如果当前节点不为空的话,始终执行此循环,此循环的目的就是让当前节点从指向next到指向pre
            //如此就可以做到反转链表的效果
            //先用next保存head的下一个节点的信息,保证单链表不会因为失去head节点的原next节点而就此断裂
            next = head.next;
            //保存完next,就可以让head从指向next变成指向pre了,代码如下
            head.next = pre;
            //head指向pre后,就继续依次反转下一个节点
            //让pre,head,next依次向后移动一个节点,继续下一次的指针反转
            pre = head;
            head = next;
        }
        //如果head为null的时候,pre就为最后一个节点了,但是链表已经反转完毕,pre就是反转后链表的第一个节点
        //直接输出pre就是我们想要得到的反转后的链表
        return pre;
    }
}
View Code

3、链表打印类

import java.util.ArrayList;
import java.util.Stack;

public class PrintList {
    //方式一:通过将链表所有节点存入ArrayList中,然后遍历ArrayList中输出的元素
    public void printList(ListNode head) {
        //遍历链表所有节点,存入ArrayList中
        ArrayList<ListNode> arrayList2 = new ArrayList<ListNode>();
        while (head != null) {
            arrayList2.add(head);
            head = head.next;
        }
        //输出值
        for (int i = 0; i < arrayList2.size(); i++) {
            System.out.print(arrayList2.get(i).val + " ");
        }
    }

    //方式二:通过将链表所有节点压入栈中,然后弹出所有节点的值,实现链表逆序打印
    public void printList2(ListNode head) {
        Stack<ListNode> stack = new Stack<ListNode>();
        //链表所有节点进栈
        while (head != null) {
            stack.push(head);
            head = head.next;
        }
        //打印栈中所有节点的值
        while (!stack.empty()) {
            System.out.print(stack.pop().val+" ");

        }
    }
}
View Code

4、测试类

public class TestMain {
    public static void main(String[] args) {

        //新建链表
        ListNode head=new ListNode(1);
        ListNode node1=new ListNode(2);
        ListNode node2=new ListNode(3);
        ListNode node3=new ListNode(4);
        head.next=node1;
        node1.next=node2;
        node2.next=node3;
        node3.next=null;

         //打印链表
        PrintList p=new PrintList();
        p.printList(head);

        //换行
        System.out.println();

        //链表逆序
        ReverseList solution=new ReverseList();
        ListNode head2=solution.reverseList(head);

        //打印逆序后的链表
        p.printList(head2);

    }
}
View Code
原文地址:https://www.cnblogs.com/hezhiyao/p/7617781.html