1.Remove Linked List Element
class Solution {
/** Iterative solution
*
*/
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==NULL) return NULL;
while(head->val==val){
if(head->next)
head=head->next;
else return NULL;
}
ListNode* cur=head;
if(cur->next){
cur=cur->next;
}else{
return head;
}
ListNode* bcur=head;
while(cur){
while(cur->val==val){
bcur->next=cur->next;
cur=cur->next;
if(cur==NULL)
return head;
}
cur=cur->next;
bcur=bcur->next;
}
return head;
}
};
class Solution {
/** recursive solution
* 注意每一层返回的是是上一层的next值,所以被删掉那个结点p依然连着它自己的next,
* 但是p的上一个会跳过p,连接p的next
*/
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==NULL) return NULL;
head->next=removeElements(head->next,val);
return head->val==val? head->next:head;
}
};
2.Add two numbers
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* cur1=l1;
ListNode* cur2=l2;
int sum=0;
ListNode* out=new ListNode(0);
ListNode* back=out;
while(cur1||cur2){
sum/=10;
if(cur1){
sum+=cur1->val;
cur1=cur1->next;
}
if(cur2){
sum+=cur2->val;
cur2=cur2->next;
}
back->next=new ListNode(sum%10);
back=back->next;
}
if(sum>=10){
back->val=(sum%10);
back->next=new ListNode(1);
}
return out->next;
}
};
3.Flatten a Multilevel Doubly Linked List
class Solution {
public:
Node* flatten(Node* head) {
if(head==NULL) return head;
Node* p=head;
while(p){
if(p->child==NULL){
p=p->next;
continue;
}
Node* curChild=p->child;
while(curChild->next)
curChild=curChild->next;
curChild->next=p->next;
if(p->next)
p->next->prev=curChild;
p->next=p->child;
p->child->prev=p;
p->child=NULL;
}
return head;
}
};
4.Copy List with random pointer
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(head==NULL) return NULL;
RandomListNode* cur=head;
RandomListNode *curNext;
while(cur!=NULL){
curNext=cur->next;
RandomListNode* temp=new RandomListNode(cur->label);
temp->next=curNext;
cur->next=temp;
cur=curNext;
}
cur=head;
while(cur!=NULL){
curNext=cur->next->next;
if(cur->random)
cur->next->random=cur->random->next;
cur=curNext;
}
RandomListNode* copyList=new RandomListNode(0);
RandomListNode* copyIter=copyList;
cur=head;
while(cur){
curNext=cur->next->next;
copyIter->next=cur->next;
copyIter=copyIter->next;
cur->next=curNext;
cur=curNext;
}
return copyList->next;
}
};