1、入门:删除链表中的元素:
题目链接
2、容易:链表求和 点击打开链接
删除链表中的元素
删除链表中等于给定值val
的所有节点。
样例
给出链表 1->2->3->3->4->5->3
, 和 val = 3
, 你需要返回删除3之后的链表:1->2->4->5
。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
ListNode *removeElements(ListNode *head, int val) {
// Write your code hereă
ListNode* H=new ListNode(INT_MIN);
H->next=head;
ListNode* h=head;
ListNode* pre=H;
while(h){
if(h->val==val){pre->next=h->next;ListNode* now=h;h=h->next;delete now;}
else{
h=h->next;
pre=pre->next;
}
}
return H->next;
}
};
2、容易:链表求和 点击打开链接
链表求和
代码:/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
ListNode *addLists(ListNode *l1, ListNode *l2) {
// write your code here
ListNode *a=new ListNode;
ListNode *head=a;
ListNode *pre;
int jin=0;
int res;
while(l1&&l2){
res=l1->val+l2->val+jin;
if(res>9)jin=1;
else jin=0;
a->val=res;
a->next=new ListNode;
pre=a;
a=a->next;
l1=l1->next;
l2=l2->next;
}
while(l1){
res=l1->val+jin;
if(res>9)jin=1;
else jin=0;
a->val=res;
a->next=new ListNode;
pre=a;
a=a->next;
l1=l1->next;
}
while(l2){
res=l2->val+jin;
if(res>9)jin=1;
else jin=0;
a->val=res;
a->next=new ListNode;
pre=a;
a=a->next;
l2=l2->next;
}
if(jin==1)a->val=1;
else
{
pre->next=NULL;delete a;
}
return head;
}
};