美文网首页
Java版链表逆置

Java版链表逆置

作者: 大海哥V | 来源:发表于2017-07-25 15:22 被阅读0次

    在此记录一下java版的链表逆置,作为之前踩过的坑,希望以后都能记住。
    包含逆置方法和测试方法,可以直接运行测试。

    class Node {
        int val;
        Node next;
        Node(int x){
            this.val = x;
        }
    }
    public class NodeReverse{
        public static void main(String[] args){
            Node head = init();
            print(head);
            head = reverse(head);
            print(head);
        }
    //create the node list
        public static Node init(){
            Node cur = new Node(0);
            Node head = cur;
            Node node;
            for(int i=1;i<=10;i++){
                node = new Node(i);
                cur.next = node;
                cur = node;
            }
            return head;
        }
    //reverse the node list
        public static Node reverse(Node head){
            Node prev = null,tmp;
            while(head!=null){
                tmp = head.next;
                head.next = prev;
                prev = head;
                head = tmp;
            }
            return prev;
        }
    //print the node list
        public static void print(Node head){
            while(head!=null){
                System.out.print(head.val+",");
                head = head.next;
            }
            System.out.println();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:Java版链表逆置

          本文链接:https://www.haomeiwen.com/subject/pugwkxtx.html