public class List203 {
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
public void add(int newval) {
ListNode newNode = new ListNode(newval);
if(this.next == null)
this.next = newNode;
else
this.next.add(newval);
}
public void iterate(ListNode head){
if (head == null){
System.out.print("This list is NULL");
} else {
while (head != null){
System.out.print(head.val + " ");
head = head.next;
}
System.out.println(" ");
}
}
}
public static ListNode removeElements(ListNode head,int val){
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
while (head != null){
if (head.val == val){
prev.next = head.next;
} else {
prev = head;
}
head = head.next;
}
return dummy.next;
}
public static void main(String[] args) {
ListNode node = new ListNode(0);
node.add(1);
node.add(1);
node.add(2);
node.add(3);
node.add(4);
node.add(5);
node.add(6);
node.iterate(node);
ListNode newnode = removeElements(node, 1);
node.iterate(node);
node.iterate(newnode);
}
}
如上代码,我在JAVA中实现了一个链表,然后调用去除链表中元素的函数,然后打印调用前和调用后的链表,结果以node为头结点的链表发生了变化,难道不是应该不变吗? 新人不太懂,求解答。