LintCode 翻转链表

题目

翻转一个链表

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

你可能感兴趣的:(链表,LintCode编程笔记)