链表节点结构
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();
}
}