🧸🧸🧸各位巨佬大家好,我是猪皮兄弟🧸🧸🧸
#include
#include
#include
typedef char BTDataType;
typedef struct TreeNode
{
BTDataType data;
struct TreeNode*left;
struct TreeNode*right;
}BT;
BT*CreateNode(BTDataType x)
{
BT*newnode=(BT*)malloc(sizeof(BT));
newnode->data=x;
newnode->left=NULL;
newnode->right=NULL;
return newnode;
}
BT*CreateTree(char* str,int *pi)
{
if(str[*pi]=='#')
{
(*pi)++;
return NULL;
}
BT*root=CreateNode(str[(*pi)++]);
root->left=CreateTree(str,pi);
root->right=CreateTree(str,pi);
return root;
}
void InOrder(BT*root)
{
if(root==NULL)
return ;
InOrder(root->left);
printf("%c ",root->data);
InOrder(root->right);
}
int main()
{
char str[100];
scanf("%s",str);
int i=0;
BT*root=CreateTree(str,&i);
InOrder(root);
return 0;
}
nowcoder链表中的节点每k个一组翻转
就是先判断有多少组len/k,然后进行组次循环,每次将这一组进行翻转
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(head==nullptr||head->next==nullptr||k<2)
return head;
ListNode* newhead=new ListNode(0);
newhead->next=head;
ListNode*prev=newhead,*next;
ListNode*cur=head;
int len=0;
while(cur)
{
cur=cur->next;
len++;
}
cur=head;
for(int i=0;i<len/k;i++)
{
for(int j=1;j<k;j++)
{
next=cur->next;
cur->next=next->next;
next->next=prev->next;
prev->next=next;
}
prev=cur;
cur=cur->next;
}
head=newhead->next;
delete newhead;
return head;
}
};
nowcoder链表相加
写一个链表逆置的函数,然后进行简单的链表相加再逆置
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* reverse(ListNode*head)
{
ListNode*newhead=new ListNode(0);
newhead->next=head;
ListNode*n1,*n2,*n3;
n1=newhead;
n2=head;
n3=head->next;
while(n2)
{
n2->next=n1;
n1=n2;
n2=n3;
if(n2)
n3=n3->next;
}
head->next=nullptr;
delete newhead;
head=n1;
return head;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
if(!head1) return head2;
if(!head2) return head1;
head1=reverse(head1);
head2=reverse(head2);
ListNode*newhead=new ListNode(0);
ListNode*tail=newhead;
int tmp=0;
while(head1||head2||tmp)
{
int val=0;
if(head1)
{
val+=head1->val;
head1=head1->next;
}
if(head2)
{
val+=head2->val;
head2=head2->next;
}
ListNode*node=new ListNode((val+tmp)%10);
tmp=(val+tmp)/10;
tail->next=node;
tail=node;
}
ListNode*head=reverse(newhead->next);
delete newhead;
return head;
}
};
nowcoder单链表的排序
要求时间复杂度O(NlogN),就先创建一个数组来存储,然后利用algorithm自带的sort函数(用的是快排时间复杂度O(NlogN) )来进行排序,再放回原链表中,空间复杂度O(N),还可以利用冒泡排序的思想,时间复杂度O(N^2),空间复杂度O(1)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
vector<int> v;
int len=0;
ListNode*cur=head;
cur=head;
while(cur)
{
v.push_back(cur->val);
cur=cur->next;
}
sort(v.begin(),v.end());
cur=head;
int start=0;
while(cur)
{
cur->val=v[start++];
cur=cur->next;
}
return head;
}
};
牛客网是个很不错的刷题软件,也希望大家能天天在上面刷刷题,大厂offer指日可待啊兄弟们。刷起来。