LintCode 翻转链表

来源:互联网 发布:2016淘宝日刷千单 编辑:程序博客网 时间:2024/05/20 11:46

翻转一个链表

样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

/** * Definition for ListNode. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int val) { *         this.val = val; *         this.next = null; *     } * } */public class Solution {    /*     * @param head: n     * @return: The new head of reversed linked list.     */    public ListNode reverse(ListNode head) {        if (head==null){            return head;        }        ListNode p=head;        ListNode next=head.next;        ListNode pre=new ListNode(0);        pre.next=head;        while(p!=null){            next=p.next;            p.next=pre;            pre=p;            p=next;        }        head.next=null;        return pre;    }}
原创粉丝点击