这道题老生常谈了,首先单链表的特点:
<1>单链表不要求逻辑上相邻的两个元素在物理位置上也相邻,因此不需要连续的存储空间。
<2>单链表是非随机的存储结构,即不能直接找到表中某个特定的结点。查找某个特定的结点时,需要从表头开始遍历,依次查找。
示意图:
代码实现:
class SingleLinkedList {
private final HeroNode head = new HeroNode(0,"","");
/**
* 反转一个链表
* @return 链表
*/
public static HeroNode reverse(HeroNode head) {
// 1.头节点为null
if (head.next == null || head.next.next == null) {
return head;
}
// 2.辅助指针
HeroNode cur = head.next;
HeroNode next = null; // 临时变量
HeroNode reverse = new HeroNode(0,"","");
// 3.指针移动,将cur中的变量放入reverse
while (cur != null) {
next = cur.next;
cur.next = reverse.next;
reverse.next = cur;
cur = next;
}
head.next = reverse.next;
return reverse;
}
public void list() {
HeroNode temp = this.head;
if (head.next == null) {
System.out.println("HeroNode{ }");
}
while (temp.next != null){
System.out.println(temp.next);
temp = temp.next;
}
}
public int size() {
int count = 0;
HeroNode temp = this.head;
while (temp.next != null){
count++;
temp = temp.next;
}
return count;
}
}
/**
* 节点
*/
class HeroNode {
int no;
String name;
String nickName;
HeroNode next; // 尾节点
public HeroNode(int no, String name, String nickName) {
this.no = no;
this.name = name;
this.nickName = nickName;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickName='" + nickName + '\'' +
'}';
}
}