• 算法刷题-1-单链表操作


     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 //练习单链表操作:给出单链表 head 和 n,要求删除单链表倒数第n个结点,并连接剩余结点
     5 //例子:1-2-3-4-5,n=2,删除后应该是:1-2-3-5
     6 typedef struct ListNode{
     7     int data;
     8     ListNode *next;
     9 }ListNode;
    10 
    11 int createList(ListNode *&head,int a[],int len)
    12 {
    13     head=(ListNode*)malloc(sizeof(ListNode));
    14     head->next=NULL;
    15     ListNode *p,*q;
    16     q=head;
    17     for(int i=0;i<len;i++)
    18     {
    19         p=(ListNode*)malloc(sizeof(ListNode));
    20         p->data=a[i];
    21         p->next=NULL;
    22         q->next=p;
    23         q=q->next;
    24     }
    25 
    26 }
    27 void print(ListNode *p)
    28 {
    29     p=p->next;
    30     while(p)
    31     {
    32         printf("%d
    ", p->data);
    33         p=p->next;
    34     }
    35 }
    36 void f(ListNode*head,int n)
    37 {
    38     ListNode *p,*q;
    39     p=q=head->next;//头节点不存储数据,从头结点的下一个开始
    40     int cnt=0;
    41     while(cnt<n)
    42     {
    43         p=p->next;
    44         cnt++;
    45     }
    46     while(p->next)//继续往下走
    47     {
    48         p=p->next;
    49         q=q->next;
    50     }
    51     q->next=q->next->next;
    52 }
    53 int main(int argc, char const *argv[])
    54 {
    55     int a[]={1,2,3,4,5};
    56     ListNode *head;
    57     int len=sizeof(a)/sizeof(int);
    58     createList(head,a,len);
    59     print(head);//单链表建立后打印它
    60     f(head,2);//删除倒数第二个结点
    61     printf("
    ");
    62     print(head);//打印处理后的单链表
    63     return 0;
    64 }

    运行结果:

     

  • 相关阅读:
    待解决问题
    [OpenCL DEBUG之路]OpenCL开发环境搭建注意点
    基于Matlab的Arnold图像置乱算法
    笔记第1篇-OpenCL基础
    Windows7_64位 NVIDIA 卡 OpenCl环境配置
    4-OpenCL进阶-GPU内存结构和性能优化
    2-OpenCL-深入理解API
    1-OpenCL-"Hello OpenCL"详解
    0-OpenCL基础知识
    3-OpenCL快速入门教程
  • 原文地址:https://www.cnblogs.com/gilgamesh-hjb/p/11846155.html
Copyright © 2020-2023  润新知