leetcode 206:Reverse Linked List

题目:
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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值