leetcode链表之反转链表

本文主要记录一下leetcode链表之反转链表网络

题目

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

 

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

 

限制:

0 <= 节点个数 <= 5000

来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。

题解

/**
 * 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 current = head;
        ListNode previous = null;
        ListNode next = null;
        while (current != null) {
            next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }
        return previous;
    }
}
  • 这里使用了current、previous、next来保存

小结

这里使用了current、previous、next来保存,初始化的时候previous及next都设置为null函数

doc

相关文章
相关标签/搜索