题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

http://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

#include<stdio.h>
#include<stdlib.h>

typedef struct ListNode {
   int val;
   struct ListNode *next;
}ListNode;

void printList(ListNode *iList);
void releaseList(ListNode *iList); 
void insertNodeByaim(ListNode *iList, int aim, int val);
void delNode(ListNode **head, int aim);

int main(int argc, char const *argv[])
{
    ListNode *list = NULL;//头结点指针

    int nodeNum = 0;
    int fistVal = 0;
    int delVal = 0;
    int aim = 0;
    int ival =0;
    scanf("%d %d ", &nodeNum, &fistVal);

    list = (ListNode *)malloc(sizeof(ListNode));//创建一个头结点
    list->next = NULL;
    list->val = fistVal;

    for (int i = 1; i < nodeNum; i++)
    {
        aim = 0;
        ival = 0;
        scanf("%d %d", &ival, &aim);
        insertNodeByaim(list, aim, ival);
    }
    
    scanf("%d", &delVal);
    //删除指定结点
    delNode(&list, delVal);
    printList(list);
    releaseList(list);

    return 0;
}

void printList(ListNode *iList)
{
   ListNode *node = iList;

   while (node != NULL)
   {
      printf("%d ", node->val);
      node = node->next;
   }
   
   printf("\n");
}

void releaseList(ListNode *iList)
{
   ListNode *tmp;
   while (iList != NULL)
   {
      tmp = iList->next;
      free(iList);
      iList = tmp;
   }
   
}

void insertNodeByaim(ListNode *iList, int aim, int val)
{
    while (iList != NULL)
    {
        if( iList->val == aim )
        {
            ListNode *tmpNode = (ListNode *)malloc(sizeof(ListNode));
            tmpNode->val = val;
            tmpNode->next = iList->next;
            iList->next = tmpNode;
        }
        iList = iList->next;
    }
    
}

void delNode(ListNode **head, int aim)
{
    ListNode *node = *head;
    if( node->val == aim )
    {
        node = node->next;
        *head = node;
        return;
    }
    while ( node->next != NULL )
    {
        if( node->next->val == aim )
        {
            node->next = node->next->next;
        }
        node = node->next;
    }
    
}

全部评论

相关推荐

见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
昨天 11:42
江西农业大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务