20.链表的基本操作

1.交换节点

(1).定义

(2).交换

(3).交换指针域

p2next指向p2本身,p1p2两个节点没有关系

合理情况应该是,p1next指向p2, p2next指向NULL

所以,上面的交换,只是把数据域成功交换了,next指针域并不符合我们要求

2.删除指定所有节点

int SListNodeDelPro(Node *head, int x)
{
    if (head == NULL)
    {
        return -1;
    }
    Node *pPre = head;
    Node *pCur = head->next;
    int flag = 0; //0没有找,1找到

    while (pCur != NULL)
    {
        if (pCur->id == x) //找到了匹配结点
        {
            //pPre的下一个指向pCur的下一个
            pPre->next = pCur->next;
            free(pCur);
            pCur = NULL;

            flag = 1;

            pCur = pPre->next;

            //break;
            continue; //跳出本次循环,重要
        }
        //pPre指向pCur位置
        pPre = pCur;
        pCur = pCur->next; //pCur指向下一个结点

    }
    if (0 == flag)
    {
        printf("没有值为%d的结点\n", x);
        return -2;
    }

    return 0;
}

3.链表翻转

int SListNodeReverse(Node *head)
{
    if (head == NULL || head->next == NULL || head->next->next == NULL)
    {
        return -1;
    }

    Node *pPre = head->next;
    Node *pCur = pPre->next;
    pPre->next = NULL;
    Node *tmp = NULL;

    while (pCur != NULL)
    {
        tmp = pCur->next;
        pCur->next = pPre;

        pPre = pCur;
        pCur = tmp;
    }

    //head->next->next = NULL;
    head->next = pPre;


    return 0;
}

4.函数递归

直接或间接调用函数本身,则该函数称为递归函数。递归函数不能定义为内联函数。

 

posted @ 2019-02-06 15:08  西贡小傻  Views(165)  Comments(0Edit  收藏  举报