雙向鍊錶基本操作以及優化可能

2022-07-21 01:06:20 字數 1722 閱讀 7633

面試時面試官要求手寫雙向鍊錶的 刪除操作,當時沒有考慮到邊界條件,導致被刷;

現在 列舉下**以及優化,作為事後反思:

typedefstruct doublelink

double_link;

/*建立乙個雙鏈表*/

double_link *createdoublelink()

/*插入節點*/

bool insertnode(double_link*head,int data)

newnodep =(double_link*)malloc(sizeof*newnodep);

if(newnodep == null)

returnfalse;

newnodep->data = data;

#if 1

/*需要插入雙向鍊錶時,遍歷到需要插入的位置,開始對待插入的節點,前驅指標和後驅指標賦值,

後驅指標固定指向下乙個節點指標,前驅需要區分 前指標是否是 頭節點。

再對 當前節點的前驅指標賦值,需要區分待插入的點是不是 尾節點*/

//1.當前節點的後驅指標

currnodep->suffix = newnodep;

//2.新節點的前驅指標

if(currnodep == head)

newnodep->prior = null;

else

newnodep->prior = currnodep;

//3.新節點的後驅指標

newnodep->suffix = nextp;

//4.下乙個節點的前驅指標

if(nextp == null)//到了尾節點處,則將頭節點的前驅指向該尾節點,這是雙向鍊錶的結構精髓所在

head->prior = newnodep;

else

nextp->prior = newnodep;

#else

if(nextp != null)

else// currnode is head

nextp->prior = newnodep;

}else

else//is the head

newnodep->suffix = null;

}#endif

returntrue;

}

/*刪除某個節點*/

bool deletenode(double_link *head, double_link *item)

//最後乙個節點時

elseif(nextp->suffix == null)// the tail

else// the mid}}

returntrue;

}

bool deletenode_opt(double_link *head, double_link *item)

//要刪除最後乙個節點

elseif(item == head->prior)

else

free(item);

item = null;

returntrue;

}

void printallnode(double_link *head)

std::cout << std::endl;

}

雙向鍊錶 基本操作

test.c define crt secure no warnings 1 include doubleslishtnode.h void test1 initdslist pushback printfdslist popback void test2 pushfront popfront vo...

雙向鍊錶基本操作

帶頭節點的雙向鍊錶操作 include include include define ok 1 define error 0 define overflow 0 using namespace std typedef int status typedef int elemtype typedef s...

雙向鍊錶基本操作

package com.bei.linkedlist auther honeysky date 2020 11 10 13 38 public class doublelinkedlistdemo 建立乙個雙向鍊錶的類 class doublelinkedlist 遍歷雙向鍊錶的方法 public ...