可惡XD!
好吧至少我順便複習了一下reverse linked list.
超過數字範圍的版本兒~~~~~
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverse(struct ListNode* head) {
struct ListNode *pre,*curr,*next;
pre = NULL;
curr = head;
next = curr->next;
while(next != NULL)
{
curr->next = pre;
pre = curr;
curr = next;
next = next->next;
}
curr->next = pre;
return curr;
}
struct ListNode* doubleIt(struct ListNode* head) {
unsigned long long num=0;
struct ListNode* ptr = head;
while (ptr != NULL)
{
num = num*10 + ptr->val;
ptr=ptr->next;
}
unsigned long long dou_num = num*2;
ptr =head;
while (dou_num>=10)
{
int tmp = dou_num%10;
dou_num /= 10;
if (ptr->next == NULL)
{
ptr->next = calloc (1, sizeof(struct ListNode));
}
ptr ->val = tmp;
ptr = ptr->next;
}
ptr->val = dou_num;
return reverse(head);
}
改成反轉之後一路相乘~再反轉回來~簡直歡樂 XD
是說久沒有reverse , 多了一行!可以再精進一下QQ
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverse(struct ListNode* head) {
struct ListNode *pre,*curr,*next;
pre = NULL;
curr = head;
next = curr->next;
while(next != NULL)
{
curr->next = pre;
pre = curr;
curr = next;
next = next->next;
}
curr->next = pre;
return curr;
}
struct ListNode* doubleIt(struct ListNode* head) {
struct ListNode* ptr = reverse(head);
head = ptr;
int carry = 0;
while (ptr != NULL)
{
int num = 2* (ptr->val)+ carry;
carry = (num>=10)?(num/10):(0);
ptr->val = num%10;
if (ptr->next == NULL && carry>0)
ptr->next = calloc (1, sizeof(struct ListNode));
ptr=ptr->next;
}
return reverse(head);
}
沒有留言:
張貼留言