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

来源:互联网 发布:硬笔书法 知乎 编辑:程序博客网 时间:2024/04/30 04:16
<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
原创粉丝点击