2.两数相加
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* cur = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* ret = cur;
int carry=0;
int value;
while(l1 || l2){
int x = l1 ? l1->val : 0;
int y = l2 ? l2->val : 0;
value = x + y + carry;
carry = value / 10;
cur->next = (struct ListNode*)malloc(sizeof(struct ListNode));
cur=cur->next;
cur->val = value % 10;
cur->next = NULL;
if(l2)l2=l2->next;
if(l1)l1=l1->next;
}
if(carry>0)
{
cur->next = (struct ListNode*)malloc(sizeof(struct ListNode));
cur=cur->next;
cur->val = 1;
cur->next = NULL;
}
return ret->next;
}
21.合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode* head=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* l3 = head;
while(l1 && l2)
{
if(l1->val < l2->val)
{
head->next = l1;
l1 = l1->next;
}
else
{
head->next = l2;
l2 = l2->next;
}
head = head->next;
}
head->next = l1 ? l1 : l2;
return l3->next;
}
19. 删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
int Length(struct ListNode* head)
{
struct ListNode* Endth = head;
int len=0;
while(Endth)
{
Endth = Endth->next;
len++;
}
return len;
}
struct ListNode* NthFromEnd(int x,struct ListNode* head)
{
struct ListNode* Findth = head;
int i=1;
int len = Length(head);
while(Findth && i<len-x+1)
{
Findth = Findth->next;
i++;
}
if(i==len-x+1)
return Findth;
else
return NULL;
}
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode* p = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
int len = Length(head);
if(n==len){
s = head;
if(head)head = head->next;
else return NULL;
free(s);
return head;
}
p = NthFromEnd(n+1,head);
if(!p)
return NULL;
else if(!p->next)
return NULL;
else
{
s=p->next;
p->next = s->next;
free(s);
return head;
}
}
141. 环形链表
给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
bool hasCycle(struct ListNode *head) {
struct ListNode* fast = head;
struct ListNode* low = head;
while(fast && fast->next)
{
fast = fast->next->next;
low = low->next;
if(fast && low && fast->val == low->val)return 1;
}
return 0;
}