实现的思路:
1.首先创建一个临时单链表single2。
2.将原来的链表single中的元素挨个取出,在取出的过程中相当于删除。
1)在取出的时候,需要将single的头指针指向它next的next headNode.next = headNode.next.next;
2) 取出res = headNode.next的时候,需要将res后边的都删掉 res.next = null
3.将每一个取出的元素放在single2中去,但是要从头开始插入如下图。
4.将single的headNode.next = single2.getHead().next;打印single即为反转或者倒序以后的单链表。
代码如下:
Person:
public class Person {
public int id;
public String name;
public Person next;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
SingleLinkedList:
public class SingleLinkedList {
private Person head = new Person(0,"");
// 添加
public void add(Person person){
Person temp = head;
// 找到最后一个再添加
while(true){
if (temp.next == null){
// 已经在最后一个了
temp.next = person;
break;
}
temp = temp.next;
}
}
// 计数
public int getCount(Person headNode){
Person temp = headNode;
int count= 0;
while(true){
if(temp.next == null){
break;
}
count++;
temp = temp.next;
}
return count;
}
// 获取头结点
public Person getHead(){
return head;
}
// 取出第n个节点
public Person getNode(Person headNode){
Person temp = headNode;
if(headNode.next == null){
throw new RuntimeException("链表为空。。。");
}
Person res = temp.next;
temp.next = temp.next.next;
res.next = null;
return res;
}
// 将节点放在第一个
public void addNodeAtFirst(Person headNode,Person node){
Person temp = headNode;
if (temp.next == null){
temp.next = node;
return;
}
node.next = headNode.next;
headNode.next = node;
}
// 显示所有的节点
public void show(Person headNode){
if(headNode.next == null){
throw new RuntimeException("链表为空。。。");
}
Person temp = headNode.next;
while(true){
if(temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
}
测试类:
public class LinkedListCount {
public static void main(String[] args) {
Person person1 = new Person(1,"zs");
Person person2 = new Person(2,"ls");
Person person3 = new Person(3,"ww");
SingleLinkedList single = new SingleLinkedList();
single.add(person1);
single.add(person2);
single.add(person3);
// 得到头结点
single.show(single.getHead());
// 反转
int count = single.getCount(single.getHead());
SingleLinkedList single2 = new SingleLinkedList();
for (int i = 0; i < count ; i++) {
Person node = single.getNode(single.getHead());
single2.addNodeAtFirst(single2.getHead(),node);
}
single.getHead().next = single2.getHead().next;
single.show(single.getHead());
}
}