Leetcode——反转链表

Posted Yawn,

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode——反转链表相关的知识,希望对你有一定的参考价值。

1. 题目

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

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

限制:
0 <= 节点个数 <= 5000

2. 题解

1.创建一个指针temp,保存下一个链表节点地址
2.依次反转即可

/**
 * 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 temp, pre = null, cur = head;
        while(cur != null){
            temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp; 
        }
        return pre;
    }
}

以上是关于Leetcode——反转链表的主要内容,如果未能解决你的问题,请参考以下文章

剑指offerJZ15——反转链表。leetcode206.反转链表

LeetCode 206. 反转链表

LeetCode 92. 反转链表 II

leetcode之反转链表图文详解

Leetcode234. 回文链表(快慢指针+反转链表)

leetcode-反转链表-46