LeetCode 206 Reverse a singly linked list.
Posted 不思蜀
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 206 Reverse a singly linked list.相关的知识,希望对你有一定的参考价值。
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
递归的办法:
/** * 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 null; if(head.next==null)return head; ListNode p=head.next; ListNode n=reverseList(p); head.next=null; p.next=head; return n; } }
非递归,迭代的办法:
if(head == null || head.next == null) return head; ListNode current = head.next; head.next = null; while(current ! = null){ ListNode temp = current.next; current.next = head; head = current; current = temp.next; } return head;
以上是关于LeetCode 206 Reverse a singly linked list.的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode-206 Reverse Linked List
LeetCode 206 链表 Reverse Linked List
LeetCode 206 Reverse Linked List
Leetcode 206: Reverse Linked List