链表相邻元素翻转,如1->2->3->4->5->6-7,翻转后变为:2->1->4->3->6->5->7。

<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>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值