从链表中删除某元素...
采取的O(n)的代价的算法。
使用两个指针,pos遍历整个链表,pre记录当前pre之前不等于val的节点(pre的移动相当于遍历了输出的链表)。当pos的值等于val时,通过pre是否为空来决定是否修改head;当pos的值不等于val时,更新pre
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode pre = null;
ListNode pos = head;
while(pos != null)
{
if(pos.val == val)
{
if(pre == null)
{
head = pos.next;
pos = pos.next;
}
else
{
pre.next = pos.next;
pos = pos.next;
}
}
else
{
pre = pos;
pos = pos.next;
}
}
return head;
}
}