WEB开发秘籍数据结构和算法分析程序员

算法笔记 - 单链表反转(Java)

2017-03-21  本文已影响501人  kMacro

单链表反转使用p、q、r三个指针配合工作,使得两个节点间的指向反向,同时用r记录剩下的链表。基本流程如下图所示:

public class ReverseList {

    public static Node reverseList(Node head){
        Node p = new Node(0);
        Node q = new Node(0);
        Node r = new Node(0);
        p = head;
        q = head.next;
        p.next = null;

        while(q!=null){
            r = q.next;
            q.next = p;
            p = q;
            q = r;
        }
        head = p;
        return head;
    }

    public static void main(String[] args) {
        int count = 9;
        Node t = new Node(1);
        Node x = t;
        for(int i = 2; i <= count; i++){
            x = (x.next = new Node(i));
        }
        t = reverseList(t);
        while(t!=null){
            System.out.print(t.val+" ");
            t = t.next;
        }
    }
    public static class Node{
        int val;
        Node next;
        Node(int v){
            val = v;
        }
    }
}

本文为作者kMacro原创,转载请注明来源:http://www.jianshu.com/p/5043be2fc875

上一篇下一篇

猜你喜欢

热点阅读