LeetCode - 206 反转链表

题目

反转一个单链表。

示例:

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

思路

  • 反转, 即修改节点的指针,从后指向前,当前节点指向前一个元素
  • 遍历过程中,需要冗余前一个元素,声明后初始化为 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 pre = null;
    // 链表中的当前节点
    ListNode current = head;
    // 临时用于节点存储
    ListNode temp = null;
    // 替换指针
    while(current != null){
        temp  = current.next;
        current.next = pre;
        pre = current;
        current = temp;
    }
    // 返回新链表的头部
    return pre;        
    }
}
发布了104 篇原创文章 · 获赞 264 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/teavamc/article/details/104138365