6.插入Node到指定的位置

if(index==0)
{
    ptr = new Node; //創立一個全新的Node
    ptr->data=value;
    ptr->next=head;
    head=ptr;
}
else
{
    i = 0;
    ptr = head;
    while (ptr != NULL)
    {
        if (i+1 == index)
        {
            temp = new Node;
            temp ->data=value;
            temp ->next = ptr ->next;
            ptr ->next = temp;
            break;
        }
        ptr = ptr ->next;
        i++;
    }
}

7.刪除指定的Node

//index代表要刪除的Node是第幾個,從0開始
if (index == 0) //刪除第一個Node必須特別處理
{
    ptr = head;
    head = head ->next;
    delete ptr;
}
else
{
    i = 0;
    ptr = head;
    while (ptr != NULL) {
        if ((i + 1) == index) {       //如果下一個Node是我們要刪除的Node
            if (ptr ->next == tail) { //如果我們要刪除的Node剛好是tail
                tail = ptr; // 因為原本的tail要被刪掉了,所以要換位置
            }
            temp = ptr ->next; //temp是我們想刪除的Node
            ptr ->next=ptr ->next ->next; //讓ptr跳過temp
            delete temp;
            break;
        }
        ptr = ptr ->next;
        i++;
    }
}

8.反轉LinkedList

Prev、Current與Next

prev = NULL;
next = NULL;
// 更新tail,因為reverse後tail會跟head互換
tail = ptr = head;

while (ptr != NULL) {
    next = ptr ->next;
    ptr ->next = prev; //轉向
    prev = ptr;
    ptr = next;
}

// 更新head
head = prev;

參考資料

results matching ""

    No results matching ""