首页 > 其他 > 详细

反转链表,时间复杂度O(n),空间复杂度O(1)

时间:2015-11-30 19:56:09      阅读:311      评论:0      收藏:0      [点我收藏+]

原理:使用三个指针,p,q指向交换的元素,r指向后续元素

代码如下:

class Node{
	int data;
	Node next; 
	Node(int data){
		this.data=data;
	}
}


 Node reverse(Node head) {
		if(head==null || head.next==null) return head;
		Node p=head,q=p.next,r=q.next;
		q.next=p;p.next=null;
		while(r!=null){
			p=q;
			q=r;
			r=r.next;
			q.next=p;
		}
		return q;
	}
}

  

反转链表,时间复杂度O(n),空间复杂度O(1)

原文:http://www.cnblogs.com/mlz-2019/p/5008053.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!