leetcode 206:Reverse Linked List

来源:互联网 发布:ubuntu gnome software 编辑:程序博客网 时间:2024/04/28 20:06

题目:
Reverse a singly linked list.
分析:
题目考察链表的反转,在这里主要是next指针的调整,利用指向前一个结点的指针before,指向后一个结点的指针followee,从而实现链表的反转。
代码:

package Code;public class LinkedList {    /**     * 链表结点类     * @author Don     *     */    public static class ListNode{        int val;        ListNode next;        ListNode(int x){val=x;}    }    /**     * 反转链表方法     * @param head     * @return     */    public static ListNode reverseList(ListNode head){        ListNode before=null;        while(head!=null){            ListNode followee=head.next;            head.next=before;            before=head;            head=followee;        }        return before;    }    /**     * 构建单链表     * @param node     * @param val     */    public static ListNode buildLinkedList(int[] a){        ListNode before=null;        for(int i=0;i<a.length;i++){            ListNode node=new ListNode(a[i]);            node.next=before;            before=node;        }        return before;    }    /**     * 打印单链表     * @param node     */    public static  void show(ListNode head){        while(head!=null){            System.out.print(head.val+".");            head=head.next;        }    }    public static void main(String[] args){        int[] a={1,2,3,4,5};        ListNode head=buildLinkedList(a);        show(head);        System.out.println();        ListNode temp=reverseList(head);        show(temp);    }}
0 0
原创粉丝点击