Java版链表逆置

在此记录一下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();
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,334评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,388评论 19 139
  • 戴斯蒙德的付出 9月2日 戴斯蒙德·迈尔斯作为17号实验体,被迫在阿尼穆斯上读取其祖先阿泰尔·伊本-拉’阿哈德的记...
    阔爷阅读 3,671评论 0 0
  • 之所以如此高调的在朋友圈和空间发我做义工的照片,就是希望能有更多的人看到,从而加入我们这个善良的团队。我们一直都是...
    酱油女王阅读 2,994评论 0 0
  • 连接查询(多表查询)内连接外连接---左外连接---右外连接 前提条件:多张表之间要存在相关联的字段 内连接 特征...
    古寒飞阅读 1,462评论 0 0