方法很笨拙,被链表给绕住了,抽空在整理一下。
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/ public class Solution {
/**
* @param head: a ListNode
* @param val: An integer
* @return: a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
// write your code here List<Integer> arr = getIndex(head,val);
return removeElements(head, val, arr);
} public static ListNode removeElements(ListNode head, int val, List<Integer> indexList) { ListNode result = head;
int i =0;
for (Integer index : indexList) {
result = deleteNode(result, index - i);
i++;
} return result; } public static ListNode deleteNode(ListNode head, int index){ //删除链表中的第一个元素
if(index==0){
head=head.next;
return head;
}
int i=1;
ListNode preNode=head;
ListNode curNode=preNode.next;
while(curNode!=null){
if(i==index){
preNode.next=curNode.next;
break;
}
preNode=curNode;
curNode=curNode.next;
i++;
}
return head;
} public static List<Integer> getIndex(ListNode head, int val){ List<Integer> arr = new ArrayList<Integer>();
if(head == null){
return arr;
}
int i = 0; if(head.val == val) {
arr.add(i);
}
ListNode curNode = head.next;
i = 1;
while (curNode != null) { if(curNode.val == val) {
arr.add(i);
}
curNode = curNode.next; i++;
} return arr;
}
}
C# 写法
public static LinkNode GetLinkNode(LinkNode head, int val)
{
LinkNode result = head;
while (result.Val == val)
{
result = result.Next;
} LinkNode preNode = result;
LinkNode curNode = preNode.Next; while (curNode != null)
{
if (curNode.Val == val)
{
preNode.Next = curNode.Next;
} preNode = curNode;
curNode = curNode.Next;
} return result;
}