剑指offer: 反转链表

    xiaoxiao2021-03-25  112

    题目:

    输入一个链表,反转链表后,输出链表的所有元素。

    思路:

    1.声明变量pre保存当前调整后的下一个节点

    2.声明变量next保存当前节点下一个节点

    3.反转当前节点的指向,并向后移动

    代码:

    /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } }*/ class Solution { public ListNode ReverseList(ListNode pHead) { // write code here if(pHead == null) return null; ListNode pre = null; ListNode next = null; while(pHead != null) { next = pHead.next; pHead.next = pre; pre = pHead; pHead = next; } return pre; } }

    转载请注明原文地址: https://ju.6miu.com/read-14962.html

    最新回复(0)