链表相邻元素翻转


链表相邻元素翻转,如 a->b->c->d->e->f-g,翻转后变为: b->a->d->c->f->e->g

import java.util.ArrayList;
import java.util.List;

class Node{
	char value;
	Node next;
	public Node(){
		
	}
	public Node(char value, Node next) {
		super();
		this.value = value;
		this.next = next;
	}
	public int getValue() {
		return value;
	}
	public void setValue(char value) {
		this.value = value;
	}
	public Node getNext() {
		return next;
	}
	public void setNext(Node next) {
		this.next = next;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return value+" ";
	}
}
public class ReverseList {
	public static void solution(List<Node> list){
		if(null == list){
			return;
		}
		if(1 == list.size()){
			return;
		}
		int p = 0;
		int q = 1;
		while(q<list.size()){
			char tmpvalue = list.get(p).value;
			list.get(p).setValue(list.get(q).value);
			list.get(q).setValue(tmpvalue);
			p+=2;
			q+=2;
		}
	}
	public static void main(String[] args) {
		Node node1=new Node('a',null);
		Node node2=new Node('b',node1);
		Node node3=new Node('c',node2);
		Node node4=new Node('d',node3);
		Node node5=new Node('e',node4);
		Node node6=new Node('f',node5);
		Node node7=new Node('g',node6);
		
		List<Node> list = new ArrayList<Node>();
		list.add(node1);
		list.add(node2);
		list.add(node3);
		list.add(node4);
		list.add(node5);
		list.add(node6);
		list.add(node7);
		
		solution(list);
		System.out.println(list);
		
		
	}
}


你可能感兴趣的:(链表相邻元素翻转)