1.创建链表问题:
ListNode *createByTail(int len)
{
ListNode *head;
ListNode *p1,*p2;
int n=0;
int num;
head=NULL;
while(n<len && cin>>num)
{
p1=new ListNode(num);
++n;
if(n==1)
head=p1;//不要写成head->next=p1;head被初始化成null,对其解引用是未定义行为。
else
p2->next=p1;
p2=p1;
}
return head;
}
2.添加元素
ListNode *AddByTail(ListNode *head, int num)
{
ListNode *p1 = new ListNode(num);//创建新节点
if (head == nullptr)
return p1; //!!如果是空的,新节点(null)为头节点。
ListNode *temp = head;
while (temp->next != nullptr)
temp = temp->next; //C++更合适用nullptr
temp->next = p1; //temp一直指向尾结点
return head;
}
3.求交集
ListNode* Intersection(ListNode *head1, ListNode *head2) {
ListNode *head3 = nullptr;//要初始化!!
if (head1 == nullptr || head2 == nullptr) return head3;
for (ListNode* p1 = head1; p1 != nullptr; p1 = p1->next)
{
for (ListNode* p2 = head2; p2 != nullptr; p2 = p2->next)
{
if (p1->val == p2->val)
{
head3 = AddByTail(head3, p1->val);
break; // 避免重复元素
}
}
}
return head3;
}
//可以用for循环!!
4.16进制char转int
int charToHex(char c) {
if(c >= '0' && c <= '9') return c - '0';
if(c >= 'A' && c <= 'F') return 10 + c - 'A';
if(c >= 'a' && c <= 'f') return 10 + c - 'a';
return 0; // 对于非法的16进制字符,这里简单返回0
}
头文件<cmath> pow(底数,指数) exp(x)e的x次方