206. Reverse Linked List

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

递归:

	public ListNode reverseList(ListNode head) {
		if(head == null || head.next == null)return head;
		ListNode p = head.next;
		ListNode q = reverseList(p);
		head.next = null;
		p.next = head;
		return q;
	}

非递归:

	public ListNode reverseList(ListNode head) {
		if (head == null || head.next == null)
			return head;
		ListNode pre = head;
		ListNode p = head.next;
		ListNode tmp = null;
		pre.next = null;
		while (p != null) {
			tmp = p.next;
			p.next = pre;
			pre = p;
			p = tmp;
		}
		return pre;	
	}



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/myfwjy/article/details/52347517
文章标签: LeetCode
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

206. Reverse Linked List

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭