2022.6.16(链表)
6月感觉有点难先写五月的过渡一下
题目描述:
给你一个单链表的引用结点
head
。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。
请你返回该链表所表示数字的 十进制值 。
我的题解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int getDecimalValue(struct ListNode* head){
struct ListNode* fir=head;
int sum=0;
while(fir){
sum+=fir->val;
fir=fir->next;
if(fir){
sum<<=1;
}
}
return sum;
}
我的思路:
依次遍历即可,把依次的加入总和看看有无下一节点,有的话向左移一位也就是*2,在加入下一个点的值
题目描述:
请编写一个函数,用于 删除单链表中某个特定节点 。在设计函数时需要注意,你无法访问链表的头节
点
head
,只能直接访问 要被删除的节点 。题目数据保证需要删除的节点 不是末尾节点 。
我的题解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void deleteNode(struct ListNode* node) {
if(node->next==NULL){
return;
}
struct ListNode* tmp=node->next;
node->val=tmp->val;
node->next=tmp->next;
free(tmp);
return;
}
我的思路:
既然删不了自己,就把自己整容成孩子,将孩子逐出宗门(什么萧炎)
题目描述:
给定单链表的头节点
head
,请反转链表,并返回反转后的链表的头节点。
我的题解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
//反向指最后将尾结点当头节点输出就行
struct ListNode* cur=head;//当前指向结点
struct ListNode* guise=NULL;
while(cur){
//什么时候下一个空就说明他已经是最后的啦
struct ListNode*next=cur->next;//保存其下一个结点
cur->next=guise;
guise=cur;
cur=next;
}
cur=guise;
return cur;
}
我的思路:
有点巧妙的方法,反转直接讲指针方向换个方向,然后迭代就行,注意的是返回的cur是空的要讲guise也就是前一个结点赋值之后再return
题目描述:
没写出来但是看懂了题解太晚了有时间再补先贴一下别人的题解
// /**
// * Definition for singly-linked list.
// * struct ListNode {
// * int val;
// * struct ListNode *next;
// * };
// */
#define MAX_SIZE 10000
int* nextLargerNodes(struct ListNode* head, int* returnSize){
struct ListNode *dummy = malloc(sizeof(struct ListNode));
dummy->next = head;
int *res = (int*)malloc(sizeof(int)*MAX_SIZE);
memset(res,0,sizeof(int)*MAX_SIZE);
struct ListNode *cur = head,*next = head->next;
if(next == NULL){
*returnSize = 1;
res[0] = 0;
return res;
}
//遍历
int i = 0;
while(cur->next != NULL){
if(next->val > cur->val){ //下一个值比当前值大,直接赋值
res[i++] = next->val;
cur = next;
next = next->next;
}
else{
while(next!= NULL){ //next 不为空,判断next 和cur的值,next 一直向后遍历,直到next 值比cur大,或者next == NULL
struct ListNode *temp = next->next;
if(next->val >cur->val){
res[i++] = next->val;
cur = cur->next;
next = cur->next;
break;
}
next = temp;
} //跳出循环时,判断是不是next == null 跳出的。
if(next == NULL){
res[i++] = 0;
cur = cur->next;
next = cur->next;
}
}
}
//最后一个必然没有比他大的下一个节点,所以最后一个值必然为0
res[i++] = 0;
*returnSize = i;
return res;
}