亚信的实习的一到笔试题,交换链表的后半部分

链表节点结构

package parameterValues;

public class LNode {
	int value;
	LNode next;
}


这是主程序

package parameterValues;


import org.junit.Test;


import sun.security.action.GetLongAction;


public class LinkListParameter {
	/**
	 * 交换链表后半部分的值,如果链表长度为偶数
	 * 则交换N/2个数
	 * 若链表长度为奇数
	 * 则交换(N+1)/2个数
	 */
	 public static void main(String[] args) {
		int a[] = {1,2,3,4,5,6};
		LNode head = initLNode(a);
		print(head);
		head = swapLinkList(head);
		print(head);
		
	}
	 
	 private static LNode swapLinkList(LNode head) {
		int length = 0;
		LNode t = head;
		while( t != null){
			t = t.next;
			length++;
		}
		
		int mid = 0;
		if(length % 2 == 0)
		{
			mid = length /2;
		}else
		{
			mid = (length+1)/2;
		}
		
		LNode newhead = new LNode();
		LNode nhead = newhead;
		newhead.value = head.value;
		newhead.next = head.next;
		System.out.println("mid ="+mid);
		int l=1;
		while(l<mid){
			LNode cur = new LNode();
			cur.value = getLNodeByIndex(head, l).value;
			cur.next = null;
			newhead.next = cur;
			newhead = cur;
			l++;
		}
		l = length-1;
		while(l>=mid && l<length){
			LNode cur = new LNode();
			cur.value = getLNodeByIndex(head,l).value;
			cur.next = null;
			newhead.next = cur;
			newhead = cur;
			l--;
		}
		print(nhead);
		return nhead;
	}


	private static LNode getLNodeByIndex(LNode head, int index) {
		LNode node = head;
		int x=0;
		while( x < index ){
			if(node.next == null ) return null;
			node = node.next;
			x++;
		}
		return node;
	}
	@Test
	public void getLNodeByIndexTest(){
		int a[] = {1,2,3,4,8,5,6,8,9};
		LNode head = initLNode(a);
		System.out.println(getLNodeByIndex(head, 7).value);
		
	}
	private static LNode initLNode(int[] a) {
		 LNode list = new LNode();
		 LNode head;
		 list.value = a[0];
		 list.next = null;
		 head = list;
		 for (int i = 1; i < a.length; i++) {
				LNode cur = new LNode();
				cur.value = a[i];
				list.next = cur;
				list = cur;
		} 
		return head;
	}


	public static void print(LNode nd){
		 System.out.println("print out LNode list");
		 while(nd != null){
			 System.out.print(nd.value+" ");
			 nd = nd.next;
		 }
		 System.out.println();
	 }
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值