反转链表 ---- Java

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:

输入:head = [1,2]
输出:[2,1]
示例 3:

输入:head = []
输出:[]

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnnhm6/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

栈方法:

/**
 * 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) {
        Stack<ListNode> stack = new Stack<>();      //新建栈结构对象
        while(head != null){        //遍历head链表
            stack.push(head);       //入栈
            head = head.next;       //更新链表节点,达到遍历效果
        }
        if(stack.isEmpty()){        //判断站是否空
            return null;
        }
        ListNode node = stack.pop();    //把第一个元素出栈并且作为链表开头
        ListNode dumpNode = node;       //把两个链表进行链接
        while(!stack.isEmpty()){        //判断栈不为空情况
            ListNode dump = stack.pop();        //出战,并且把出栈元素给node链表
            node.next = dump;
            node = node.next;
        }
        node.next = null;               //把尾节点设置为空
        return dumpNode;                //返回链表   
    }
}

新链表方法:

/**
 * 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) {
        ListNode resultNode = null;     //新链表
        while(head != null){
            ListNode node = head.next;  //保存下一节点
            head.next = resultNode;     //把下一节点的下一节点的链接链接到新链表
            resultNode = head;          //为新链表的节点进行赋值
            head = node;                //更新节点
        }
        return resultNode;
    }
}
posted @ 2022-01-23 15:30  网抑云黑胶SVIP用户  阅读(39)  评论(0编辑  收藏  举报