剑指Offer——反转链表

By AverageJoeWang
 标签:

反转链表

  • 题目描述
    输入一个链表,反转链表后,输出链表的所有元素。

  • 解题思路

    • 1->2->3->4->5
    • 1<-2<-3 4->5
  • 代码实现

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null) return null;
        ListNode reverseNode = null;
        ListNode currentNode = null;
        while (head != null){
            currentNode = head.next;
            head.next = reverseNode;
            reverseNode = head;
            head = currentNode;
        }
        return reverseNode;
    }
}