leetcode:#206 反转链表

leetcode:#206 反转链表

题目详情

java实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution { //头插法
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode reverseHead = head;
        ListNode currentNode = head.next;
        reverseHead.next = null;
        while(currentNode != null) {
            ListNode nextNode = currentNode.next;
            currentNode.next = reverseHead;
            reverseHead = currentNode;
            currentNode = nextNode;
        }

        return reverseHead;
    }
}
上一篇:实现链表


下一篇:二叉树及其遍历方法---python实现