LinkedListTest1

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;
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值