java 链表反转_Java实现链表反转的一个示例

粘一下完整的代码:

Code:

package chapter4;

import java.util.HashMap;

import java.util.Map;

public class ReverseLinkedListDemo {

public static void main(String[] args) {

ReverseLinkedListDemo reverseLinkedListDemo = new ReverseLinkedListDemo();

Entry[] newTable = new Entry[1];

Entry E2 = new Entry(11, "E2-key", "E2-value", null);

Entry E1 = new Entry(1, "E1-key", "E1-value", E2);

Entry[] src = {E1};

reverseLinkedListDemo.printLinkedEntry(src);

reverseLinkedListDemo.transfer(src, newTable);

System.out.println("===================华丽的分隔线===================");

reverseLinkedListDemo.printLinkedEntry(newTable);

}    private void printLinkedEntry(Entry[] newTable) {

for (Entry entry : newTable) {

System.out.println("entry:" + entry);

if (entry != null && entry.next != null) {

System.out.println("entry.next:" + entry.next);

}

}

}

/**

* Transfers all entries from current table to newTable.

*/

void transfer(Entry[] src, Entry[] newTable) {

for (int j = 0; j < src.length; j++) {

Entry e = src[j];

if (e != null) {

src[j] = null;

do {

Entry next = e.next;

int i = 0;

e.next = newTable[i];

newTable[i] = e;

e = next;

} while (e != null);

}

}

}

static class Entry implements Map.Entry {

final K key;

V value;

Entry next;

final int hash;

/**

* Creates new entry.

*/

Entry(int h, K k, V v, Entry n) {

value = v;

next = n;

key = k;

hash = h;

}        public final K getKey() {

return key;

}

public final V getValue() {

return value;

}

public final V setValue(V newValue) {

V oldValue = value;

value = newValue;

return oldValue;

}

public final boolean equals(Object o) {

if (!(o instanceof Map.Entry))

return false;

Map.Entry e = (Map.Entry) o;

Object k1 = getKey();

Object k2 = e.getKey();

if (k1 == k2 || (k1 != null && k1.equals(k2))) {

Object v1 = getValue();

Object v2 = e.getValue();

if (v1 == v2 || (v1 != null && v1.equals(v2)))

return true;

}

return false;

}        public final int hashCode() {

return (key == null ? 0 : key.hashCode()) ^                    (value == null ? 0 : value.hashCode());

}        public final String toString() {

return getKey() + "=" + getValue();

}        /**

* This method is invoked whenever the value in an entry is

* overwritten by an invocation of put(k,v) for a key k that's already

* in the HashMap.

*/

void recordAccess(HashMap m) {

}

/**

* This method is invoked whenever the entry is

* removed from the table.

*/

void recordRemoval(HashMap m) {

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值