代码如下:
public class LinkedList {
public static void main(String[] args) {
Node node = new Node(1, "zza", "tommy");
Node node2 = new Node(2, "michael", "ma");
Node node3 = new Node(3, "frank", "asd");
List list = new List();
list.add(node);
list.add(node2);
list.add(node3);
list.show();
list.exchangeInfo(1, "1", "1");
list.show();
}
}
class Node{
String name;
String nikeName;
Integer no;
Node next;
public Node(Integer no, String name, String nickName) {
this.name = name;
this.no = no;
this.nikeName = nickName;
}
@Override
public String toString() {
return "Node{" +
"name='" + name + '\'' +
", nikeName='" + nikeName + '\'' +
", no=" + no +
'}';
}
}
class List {
private Node head = new Node(null, null, null);
public void add(Node node) {
Node index = head;
while(index.next != null) {
index = index.next;
}
index.next = node;
}
public void show() {
Node index = head.next;
while(index != null) {
System.out.println(index);
index = index.next;
}
}
public void exchangeInfo(int no, String name, String nickName) {
if (head.next == null) {
return;
} else {
Node index = head.next;
boolean flag = false;
while(true) {
if (index == null) {
break; // 链表遍历结束
}
if (index.no == no) {
flag = true;
break;
}
index = index.next;
}
if (flag) {
index.nikeName = nickName;
index.name = name;
} else {
throw new RuntimeException("没找到节点" + no);
}
}
}
}
在上述代码中的链表修改节点的操作:
public void exchangeInfo(int no, String name, String nickName) {
if (head.next == null) {
return;
} else {
Node index = head.next;
boolean flag = false;
while(true) {
if (index == null) {
break; // 链表遍历结束
}
if (index.no == no) {
flag = true;
break;
}
index = index.next;
}
if (flag) {
index.nikeName = nickName;
index.name = name;
} else {
throw new RuntimeException("没找到节点" + no);
}
}
}
在遍历链表中使用了一个指针用啦游走遍历:index
,如代码所示,当遍历找到我们的需要修改的节点时,修改的操作是对index这个指针节点进行的,并没有对实际的节点进行操作,但是为什么最后得到的结果却是修改之后的结果呢?