Problem:
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
Solution:
这个题目真的很简单,但是被我想复杂了。其实他要写的方法就是删除当前节点的方法,我以为是要把所有节点删除(除了最后一个),然后想了半天也没搞定。
所谓删除,就是把指针移到下下个,然后把自己的值和后面一个换掉。那么相当于和后面一个换位置,然后删除后一个数。
代码如下:
public class Solution {
public void deleteNode(ListNode node) {
//当该节点不为空,执行
if(node != null){
System.out.println(node.val);
node.val = node.next.val;
node.next = node.next.next;
}
}
}
Problem 2:
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
Solution:
作为一个初学者,总是不清楚如何通过返回一个结点得到整个列表。经过学习才知道,返回头结点,就可以通过引用一直往下得到整个列表了。
另外,在写程序的时候犯了一个大错,用数组的方法去思考了。直接新建一个LinkedList,然后用新LinkedList指向原来链表中不等于val的结点。这是完全不对的。一个链表指向另外一个链表了。
因此要在一个链表中,用两个引用去操作。一个引用用来判断该结点是否等于val,另一个引用去指向不等于val的结点,获得新的链表。
程序如下:
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode node = new ListNode(0);
node.next = head;
ListNode p = node;
if(head == null){
return null;
}
while(head!=null){
if(head.val == val ){
p.next = head.next;
}else{
p = p.next;
}
head = head.next;
}
return node.next;
}
}