导航

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

Posted on 2015-11-30 18:44  骄阳照林  阅读(2243)  评论(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;
	}
}