Delete a Node
Delete a Node
+ 39 comments Recursive solution is nice and neat. Linked lists are often naturally handled recursively:
Node Delete(Node head, int position) { if (position == 0){ return head.next; } head.next = Delete(head.next, position-1); return head; }
+ 5 comments Can anyone help me I am getting this error and I dont know why this is coming Please help
Solution.java:77: error: Illegal static declaration in inner class Solution.Result public static SinglyLinkedListNode deleteNode(SinglyLinkedListNode llist, int position) { ^ modifier 'static' is only allowed in constant variable declarations Solution.java:122: error: cannot find symbol SinglyLinkedListNode llist1 = deleteNode(llist.head, position); ^ symbol: method deleteNode(SinglyLinkedListNode,int) location: class Solution 2 errors****
+ 6 comments Magic C++ solution
Elegant as the recursive one - just 3 lines of code
Only faster, less memory footprint and way cooler!
It essentially just finds the address of the node that's to be deleted and places the next node's address there.
(Actually just replaces the pointer values, using pointers to pointers..)
Code:
SinglyLinkedListNode* deleteNode(SinglyLinkedListNode* head, int n) { auto x=&head; for(int i=0;i<n;i++,x=&(*x)->next); *x=(*x)->next; return head; }
+ 2 comments Problems seems to be broken with C++.
Node* Delete(Node *head, int position) { if(position == 0){ Node* next = head->next; delete head; return next; } Node* current = head; Node* prev = head; for(int i = 0; i < position; i++){ prev = current; current = current->next; } prev->next = current->next; delete current; return head; }
Output is correct, however it's not breaking lines correctly:
23 13 12 4351
+ 1 comment Why is this code showing error in test case 2?
SinglyLinkedListNode *prev,*t; prev = NULL; t = head; if( position == 0 ){ head = head->next; delete(head); } while( position > 0 ){ prev = t; t = t->next; position--; } if(t != NULL){ prev->next = t->next; delete(t); } return head;
Sort 680 Discussions, By:
Please Login in order to post a comment