/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* deleteMiddle(ListNode* head) { ListNode* o=head; ListNode* t=head; ListNode* prev=head; if(head->next==NULL) { return head=NULL; } if(head->next->next==NULL) { delete head->next; head->next=NULL; return head; } while(t!=NULL && t->next!=NULL) { if(t!=head) prev=prev->next; o=o->next; t=t->next->next; } prev->next=o->next; delete o; return head; } };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter