單鏈表的基本操作

2021-08-20 18:54:23 字數 1539 閱讀 7896

單鏈表的插入,反轉,判斷是否有環,深複製,以及帶random指標的單鏈表的深拷貝

#includeusing namespace std;

struct listnode

};//單向鍊錶的反轉,三個指標進行操作,很簡單

listnode *reverselist(listnode *head)

head->next = null;

head = p1;

return head;

}//判斷鍊錶是不是帶環,如果帶環,找出環的入口節點

bool hasloop(listnode *head, listnode *intrance)

} if (tag)//說明存在環 }

intrance = p1;

return tag;

}//鍊錶的深拷貝,鍊錶可能有環

listnode *deepcopy(listnode *head)

q->next = new listnode(intrance->val);

listnode *cur = q->next;

p = intrance->next;

q = q->next;

while (p != intrance)

q->next = cur;

return copy->next;

} else //鍊錶無環

q->next = null;

return copy->next; }}

//單鏈表節點的插入

listnode *insert(listnode *head, int num)

listnode *pre = head;

listnode *p=null; //記住前驅結點

while (num > pre->val && pre->next!=null)

if (num <= pre->val)

else

}else//該節點應該被插入到最後乙個位置

return head;

}//帶隨機節點的鍊錶的深複製

struct randomlistnode

};randomlistnode *copyrandomlistnode(randomlistnode *head)

pre = head;

randomlistnode *cur = pre->next;

while (pre)

pre = head;

cur = pre->next;

randomlistnode *copy = cur;

while (cur->next)

pre->next = null;

return copy;

}void print(listnode *head)

}int main()

head=reverselist(head);

print(head);

system("pause");

return 0;

}

單鏈表基本操作

include include include include includeusing namespace std typedef struct node node,plinklist plinklist createfromhead node pstnode node malloc sizeof...

單鏈表基本操作

單鏈表的初始化,建立,插入,查詢,刪除。author wang yong date 2010.8.19 include include typedef int elemtype 定義結點型別 typedef struct node node,linkedlist 單鏈表的初始化 linkedlist...

單鏈表基本操作

include using namespace std define namelenth 20 define ok 0 define error 1 typedef struct flagnode node 生成結點 inline node newnode 銷毀化煉表 void destroylin...