继上周的阿拉伯数字转换成罗马数字,顺便把罗马数字转阿拉伯数字的也编写一下。
1.题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题目解析:这道题主要运用两个规则,其一当左边的罗马数字比右边的罗马数字大时,则相加;反之,则想减。
程序如下:
class Solution {
public:
int romanToInt(string s) {
int graph[400];
graph['I']=1;
graph['V']=5;
graph['X']=10;
graph['L']=50;
graph['C']=100;
graph['D']=500;
graph['M']=1000;
int sum=graph[s[0]];
int len=s.length();//注意:在函数定义的s,不能调用函数size()求长度
for(int i=0;i<len-1;i++)
{
if(graph[s[i]]>=graph[s[i+1]])
sum+=graph[s[i+1]];
else
sum=sum+graph[s[i+1]]-2*graph[s[i]];
}
return sum;
}
};
这是一道运用递归解决的链表题。
2.题目:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
题目解析:
此题是有一个循环的,即每两个节点互换,这样我们就可以用到递归,当然也有普通循环解法。
递归程序:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* stamp = head->next;
head->next = swapPairs(stamp->next);
stamp->next = head;
return stamp;
}
};
循环程序:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode **p = &head, *a, *b;
while ((a = *p) && (b = a->next)) {
a->next = b->next;
b->next = a;
*p = b;
p = &(a->next);
}
return head;
}
};