translation
removes all elements with a value of Val from a linked list. For examplegiven: 1 -->2 -->6 -->3 -->4 -->5 -->6, Val = 6returns: 1 -->2 -->3 -->4 -->5
Original
Remove all elements from a linked list ofIntegers that has value Val. ExampleGiven:1- - 2- - 6- - 3- - 4- - 5- - 6, val =6Return:1- - 2- - 3- - 4- - 5
Analysis
Yesterday noon received a good news so long can not calm, repeatedly this problem has been wrong, the more chaotic, after all, logic has been in the Cloud nine ...
Deleted yesterday's code this morning to re-come, once passed.
I have a new set of 3 indexes:
newHead,指向头部,用于最后返回pre,指向移动中节点的前一个节点cur,指向移动中的节点
I will not draw the picture ... Through the continuous circulation of the cur, while the internal judge whether the value of cur is equal to the given Val, respectively, the corresponding operation. The last pre and Cur moved to the back of the list, and the task of returning the entire list was given to Newhead.
Another key problem is that the above approach is to compare the second node of the list to Val, then the first node? Yesterday's train of thought is really too cumbersome, yesterday was used two while loop, the second is said above, the first to determine whether the element of the list head is equal to Val.
But a better approach is to use newhead directly. Not before the second element of the list to the last element to make a judgment, return to return to the Newhead or newhead the next element is not good?
Code
/*** Definition for singly-linked list.* struct ListNode {* int val;* listnode *next;* listnode (int x): V Al (x), Next (NULL) {}*};*/ class solution {public:listnode* removeelements (listnode* head, intVal) {if(!head)returnNULL; ListNode *pre = head, *cur = head->next, *newhead = pre;if(!cur)returnPre->Val==Val? Null:pre; while(cur) {if(cur->Val==Val) Pre->next = cur->next;ElsePre = pre->next; Cur = cur->next; }if(newhead->Val==Val)returnnewhead->next;Else returnNewhead;; }};
Leetcode 203 Remove Linked list Elements (remove linked list element) (*)