<span style="font-size:14px;">package test;
/*
* 链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g。
*/
public class NodeReverse {
public static void main(String[] args) {
int a[] = { 1, 2, 3, 4, 5, 6, 7 };
Node root = new Node(a[0]);
Node head = root;
for (int i = 1; i < a.length; i++) {
Node node = new Node(a[i]);
head.next = node;
head = node;
}
root = reverseAdjacentNode(root);
System.out.print("相邻元素翻转后:");
while (root != null) {
System.out.print(root.data);
root = root.next;
if(root != null) {
System.out.print("->");
}
}
}
private static Node reverseAdjacentNode(Node root) {
Node head = root;
Node p, q = null;
if (root.next != null) {
root = root.next; //根结点为第二个结点
} else {
return root;
}
int flag = 0; //判断P是否为第一个结点
p = head;
q = head.next;
while(p!= null) {
if(flag == 0) { //p为第一个结点
p.next = q.next;
q.next = p;
flag = 1;
} else {
if(p.next == null) {
break;
}
head.next = q;
p.next = q.next;
q.next = p;
}
head = p; //保留下一个p前面的结点
p = p.next;
q = p.next;
}
return root;
}
}
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
</span>