您的位置:首页 > 其它

LeetCode206: 反转链表

2018-03-29 12:14 645 查看
反转一个单链表。进阶:
链表可以迭代或递归地反转。你能否两个都实现一遍?
思路: https://blog.csdn.net/fx677588/article/details/72357389
1. 首先是迭代的反转链表



方式如上图所示, 
2. 利用递归
代码:/**
* 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 next = null;
// while(head!=null){
// next = head.next;
// head.next = pre;
// pre = head;
// head = next;
// }
// return pre;
if(head==null || head.next==null){
return head;
}
ListNode h = reverseList(head.next);
head.next.next = head;
head.next = null;
return h;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: