lintcode--翻转链表

来源:互联网 发布:mac安装win10时蓝屏 编辑:程序博客网 时间:2024/05/17 22:32

翻转一个链表

样例

给出一个链表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 {


    public ListNode reverse(ListNode head) {
        // write your code here
    
        ListNode  pre = null;
        ListNode temp = null;
        while(head!=null){
            temp = head.next;//保存下一节点
            head.next = pre;
            //向后移动
            pre = head;
            head = temp;//下一个
        }
        //返回前指针;
        return pre;
    }


}


原创粉丝点击