[英]Deleting a Node after a given position and head in a singly linked list
Did I miss anything in the below code .我是否错过了以下代码中的任何内容。 The code is about deleting a Node from a linkedlist given its head and position.
该代码是关于从给定其头部和位置的链表中删除一个节点。 My program is not passing all the test cases .
我的程序没有通过所有的测试用例。
Node Delete(Node head, int position) {
// Node temp=head;
int count=1;
if(position==0){
head=head.next;
return head;
}
if(position==1){
head=head.next.next;
return head;
}
if(position>1){
Node temp=head;
while(count<position){
count++;
temp=temp.next;
}
temp.next=temp.next.next;
}
return head;
}
Input输入
4 4
3 3
1 2 3 1 2 3
0 0
3 3
1 2 3 1 2 3
1 1
3 3
1 2 3 1 2 3
2 2
5 5
4 3 2 5 1 4 3 2 5 1
2 2
My output我的输出
23 23
12 4351 12 4351
Expected output预期输出
23 13 12 4351 23 13 12 4351
public static Node Delete(Node head, int position) {
Node node = head;
Node prevNode = null;
int index = 0;
if (head == null && position == 0){
return head;
}
if (head != null && position == 0){
head = null;
head = node.next;
}
if (position > 0){
while(index<position){
prevNode = node;
node = node.next;
index = index + 1;
}
prevNode.next = node.next;
node = null;
}
return head;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.