1.题目要求:
给你一个 非空 链表的头节点 head ,表示一个不含前导零的非负数整数。
将链表 翻倍 后,返回头节点 head 。
2.题目代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* doubleIt(struct ListNode* head){
struct ListNode* cur = head;
int count = 0;
//1.遍历链表,得到结点个数
while(cur){
count++;
cur = cur->next;
}
int* number = (int*)malloc(sizeof(int) * count);//2.根据结点个数用malloc申请数组
int j = 0;
cur = head;
//3.把链表的结点放入数组
while(cur){
number[j] = cur->val;
j++;
cur = cur->next;
}
//4.给每个数组都乘以2
for(int i = 0;i < j;i++){
number[i] *= 2;
}
//5.进行进位
for(int i = j - 1;i > 0;i--){
if(number[i] > 9){
number[i] %= 10;
number[i - 1] += 1;
}
}
//6.判断数组第一个数是否大于9
if(number[0] > 9){
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
newnode->val = number[0] / 10;
newnode->next = head;
head = newnode;
cur = head;
cur = cur->next;
cur->val = number[0] % 10;
int i = 1;
cur = cur->next;
while(cur){
cur->val = number[i];
i++;
cur = cur->next;
}
return head;
}else{
cur = head;
int i = 0;
while(cur){
cur->val = number[i];
i++;
cur = cur->next;
}
return head;
}
}