本文主要是介绍LeetCode 206 Reverse Linked List (逆置链表),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Reverse a singly linked list.
A linked list can be reversed either iteratively or recursively. Could you implement both?
题目链接:https://leetcode.com/problems/reverse-linked-list/
题目分析:链表的逆置,迭代和递归分别实现
迭代法:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
public class Solution {public ListNode reverseList(ListNode head) {if(head == null) {return head;}ListNode cur = head.next;head.next = null;while(cur != null) {ListNode tmp = cur.next;cur.next = head;head = cur;cur = tmp;}return head;}
}
递归法:所谓递归,就当有个栈在维护
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
public class Solution {public ListNode reverseList(ListNode head) {if(head == null || head.next == null) {return head;}ListNode Rhead = reverseList(head.next);head.next.next = head;head.next = null;return Rhead;}
}
这篇关于LeetCode 206 Reverse Linked List (逆置链表)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!