LintCode 翻转链表

来源:互联网 发布:钉钉 阿里云企业邮箱 编辑:程序博客网 时间:2024/05/20 14:27

题目

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

题目中默认的节点类

 public class ListNode {     int val;      ListNode next;     ListNode(int val) {          this.val = val;          this.next = null;      }  }

代码

public class Solution {    /**     * @param head: The head of linked list.     * @return: The new head of reversed linked list.     */    public ListNode reverse(ListNode head) {        // write your code here        if(head == null) return head;        ListNode pre = null;        ListNode cur = null;        ListNode next = null;        cur = head;        while(cur!=null){            next = cur.next;            cur.next =  pre;            pre = cur;            cur = next;        }        head = pre;        return head;    }}

参考:
http://blog.csdn.net/xia744510124/article/details/50038461