力扣59题和203题

力扣59题-螺旋矩阵

题目描述

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

代码及思路

代码

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
int** generateMatrix(int n, int* returnSize, int** returnColumnSizes) {
    *returnSize=n;
    *returnColumnSizes=(int*)malloc(sizeof(int)*n);
    int** nums=(int**)malloc(sizeof(int*)*n);//因为生成的是一个n×n的矩阵,所以只有n行
    for(int i=0;i<n;i++)
    {
        nums[i]=(int*)malloc(sizeof(int)*n);//每一个nums指针都有n个int型的空间
        (*returnColumnSizes)[i]=n;
    }
    int i=0,j=0;
    int startx=0,starty=0;
    int offset=1;
    int counst=1;
    int loop=n/2;
    while(loop--){
        i=startx;
        j=starty;
        for(j=starty;j<n-offset;j++){
            nums[startx][j]=counst;
            counst++;
        }
        for(i=startx;i<n-offset;i++){
            nums[i][j]=counst;
            counst++;
        }
        for(;j>starty;j--){
            nums[i][j]=counst;
            counst++;
        }
        for(;i>startx;i--){
            nums[i][j]=counst;
            counst++;
        }
        offset=offset+1;
        startx++;
        starty++;
    }
    if(n%2==1){
        nums[n/2][n/2]=counst;
    }
    return nums;
}

思路
模拟顺时针方阵的过程:
1、从左到右画上行
2、从上到下画右列
3、从右到左画下行
4、从下到上画左列
首先判断每个边要循环几次,然后每次循环里面用4个for循环,从左到右,画上行,从上到下,画右列,从右到左,画下行,从下到上画左列。再判断若n是奇数,则为矩阵最中间的数,nums[n/2][n/2].

力扣203-移除链表元素

题目描述

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

代码及思路

代码

在这里插入代/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    while(head!=NULL&&head->val==val){
       struct ListNode* temp;
        temp=head;
        head=head->next;
        free(temp);
    }
        struct ListNode*cur=head;
       while(cur!=NULL&&cur->next!=NULL){
        if(cur->next->val==val){
           struct  ListNode*temp;
            temp=cur->next;
            cur->next=cur->next->next;
            free(temp);
        }
        else {
            cur=cur->next;
        }
       }
       return head;
}码片

思路
如果头节点为要删除的元素,则令下一个结点为头节点,释放头节点,要注意用while循环,而不是if循环,因为有可能现在新的头节点也是要删除的。如果要删除的是其他点的结点,则用循环遍历每个结点进行判断,若找出,则定义一个临时指针,指向要删除的节点,让其前一个指向后一个,释放它,最后返回头节点。

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值