翻转单链表中的K个节点——By Java

public class LinkListReverseK {

	/**
	 * 题目要求:给定一个单链表和一个参数K,要求翻转K个节点,且翻转后剩余的节点数大于K则继续翻转,否则停止;
	 * 例如:链表:1,2,3,4,5,6,7,8,9,10;K=4;则应有结果:8,7,6,5,4,3,2,1,9,10;
	 * 思路:在传统的链表翻转的基础上,计算出一共需要翻转的节点数目,每次循环只改变一个节点的指向直至计数器为0;
	 * @param args
	 * @author Adai
	 * @since 2013/06/24
	 */
	private static class LinkNode{
		private int data;
		private LinkNode next;
		/**
		 * @return the data
		 */
		public LinkNode(){
			
		}
		public LinkNode(int d){
			this.data=d;
			this.next=null;
		}
		public int getData() {
			return data;
		}
		/**
		 * @param data the data to set
		 */
		public void setData(int data) {
			this.data = data;
		}
		/**
		 * @return the next
		 */
		public LinkNode getNext() {
			return next;
		}
		/**
		 * @param next the next to set
		 */
		public void setNext(LinkNode next) {
			this.next = next;
		}
		
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] a={1,2,3,4,5,6,7,8,9,10};
		LinkListReverseK llrk=new LinkListReverseK();
		LinkNode h=llrk.Init(a);
		LinkNode r=llrk.LinkReverse(h,4);
		while(r!=null){
			System.out.println(r.getData());
			r=r.next;
		}
	}
	private LinkNode Init(int[] a){
		LinkNode head=null;
		LinkNode last=null;
		for(int i=0;i<a.length;i++){
			LinkNode one=new LinkNode(a[i]);
			if(last!=null){
				last.next=one;
				last=one;
			}
			if(i==0){
				head=one;
				last=one;
			}
		}
		return head;
	}
	private LinkNode LinkReverse(LinkNode head,int k){
		if(head==null) return null;
		if(k<1) return head;
		LinkNode run=head;
		int count=0;
		while(run!=null){
			count++;
			run=run.next;
		}
		if(count<k){
			return head;
		}
		int times=count/k;
		times=times*k;
		System.out.println("times="+times);
		LinkNode p=head;
		LinkNode q=null;
		LinkNode r=null;
		while(times>0){
			System.out.println("dd:"+p.getData()+":"+times);
			q=p.next;
			p.next=r;
			r=p;
			p=q;
			times--;
		}
		head.next=q;
		return r;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值