Q24、(链表):链表操作,单链表就地逆置

题目:

链表操作,单链表就地逆置

 

解题思路:

很经典的一个链表算法题..其实需要注意的就是在改变链表的时候一定要维持你需要的指针的相对位置...

其实挺简单的...

 

public class Q24 {
	public static void main(String[] args) {
		//建立链表
		Node head = new Node(1);

		Node before = head;
		Node now = null;
		for(int i = 2;i<10;i++)
		{
			now = new Node(i);
			before.next = now;
			before = now;
		}
		now = head;
		while(now!=null)
		{
			System.out.println(now.element);
			now = now.next;
		}
		
		//链表就地逆置
		head = Reverse(head);
		
		while(head!=null)
		{
			System.out.println(head.element);
			head = head.next;
		}
		
	}
	
	public static Node Reverse(Node head)
	{
		if(head == null)
		{
			System.out.println("ERROR");
			return null;
		}
		Node p = null;
		Node q = null;
		Node r = head;
		
		while(r != null)            //关键代码..就是必须要全部指针都到了预期的位置再改变指针指向........Notice
		{
			p = q;
			q = r;
			r = r.next;
			
			if(q != null)
				q.next = p;
			
		}
		
		return q;
	}
}

class Node{
	public Node next = null;
	public int element = 0;
	
	public Node(int e) {
		// TODO Auto-generated constructor stub
		this.element = e;
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值