package com.qbsea.arithmetic.linked;
public class LinkedListTest1 {
public static void printLinkedList(LinkedList linkedList) {
Node current = linkedList.getHead();
while (current.next != null) {
System.out.print(current.getData() + "-->");
current = current.next;
}
System.out.println(current.getData());
}
public static void main(String[] args) {
// 往链表里增加五个数
LinkedList linkedList = new LinkedList();
linkedList.add(new Node("a1"));
linkedList.add(new Node("a2"));
linkedList.add(new Node("a3"));
linkedList.add(new Node("a4"));
linkedList.add(new Node("a5"));
linkedList.add(new Node("b1"));
linkedList.add(new Node("b2"));
linkedList.add(new Node("b3"));
linkedList.add(new Node("b4"));
linkedList.add(new Node("b5"));
printLinkedList(linkedList);
Node quickP = linkedList.getHead();// 快速指针
Node slowP = linkedList.getHead();// 慢指针
int i = 1;
while (quickP.next != null) {//尾节点时退出了
if (i % 2 == 0) {
slowP = slowP.getNext();
}
quickP = quickP.getNext();
i++;
}
System.out.println("quickP=" + quickP.getData());
System.out.println("slowP=" + slowP.getData());
quickP = linkedList.getHead();// 快速指针移到链表头
slowP = slowP.next;
while (slowP!= null) {//尾节点时也执行一把然后退出
Node nodea = quickP.next;
quickP.next = slowP;
Node nodeb = slowP.next;
if(nodeb==null) {
break;//链表尾
}
slowP.next = nodea;
quickP = nodea;// xxx
slowP = nodeb;
}
printLinkedList(linkedList);
}
public static class LinkedList {
private Node head;// 头指针
private Node tail;// 尾指针
public void add(Node node) {
if (head == null) {
head = node;
tail = node;
return;
}
tail.next = node;
tail = node;
}
// LinkedList的set and get method
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
public Node getTail() {
return tail;
}
public void setTail(Node tail) {
this.tail = tail;
}
}
public static class Node {
private Node next;// 指针
private String data;
Node(String data) {
this.data = data;
}
// set and get method
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
}