java 实现单链表反转Reverse Linked List

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
       ListNode curr = head;
       ListNode preNode = null;//反转后前节点
       ListNode nextTemp = null; //next node
       
        while (curr != null){
            nextTemp = curr.next;//获得当前节点
            curr.next = preNode; //当前节点为前节点
            preNode = curr;
            curr = nextTemp;
        }
        return preNode;
    }
}

 

posted on 2019-10-08 21:45  ptbx  阅读(472)  评论(0)    收藏  举报