1. 程式人生 > >帶頭結點的單鏈表操作(頭插法)-c++

帶頭結點的單鏈表操作(頭插法)-c++

span str out let 單鏈表 null 頭結點 操作 truct

c++編寫 帶頭結點的單鏈表操作(頭插法)(和c語言差不多)

#include<iostream>
#include<conio.h>
using namespace std;
typedef int ElemType;
typedef struct LNode
{
    ElemType data;
    struct  LNode *next;
    
}LNode;

LNode *create_head()//創建頭結點
{
    LNode *head = (LNode *)malloc(sizeof(LNode));
    
if (!head)return NULL; head->data = NULL; head->next = NULL; return head; } LNode *create_node(ElemType data)//創建結點 { LNode *newnode = (LNode*)malloc(sizeof(LNode)); if (!newnode)return NULL; newnode->data=data; newnode->next = NULL; return newnode; }
void Insert_byHead(LNode *head,ElemType data)//頭插法鏈接 { LNode *newnode = create_node(data); newnode->next = head->next; head->next = newnode; } int EmptyList(LNode *head) { if (head->next == NULL)return 1; return 0; } void Print_List(LNode *head)//遍歷打印 { if
(EmptyList(head))return; LNode *p = head->next; while (p) { cout << p->data; p = p->next; } } int Len_Get(LNode *head)//遍歷獲取長度 { int len = 0; LNode *p = head->next; while (p) { p = p->next; len++; } return len; } void Insert_Node(LNode *head, ElemType data,int pos)//插入第幾個結點後 { if (EmptyList(head))return; if (pos > Len_Get(head)) { cout << "error"; return; } LNode *newnode = create_node(data); LNode *p = head; LNode *tmp; int i = 0; while (i != pos) { p = p->next; i++; } tmp = p->next; p->next = newnode; newnode->next = tmp; } void Delete_Node(LNode *head,int pos)//刪除結點 { if (EmptyList(head))return; if (pos > Len_Get(head)) { printf("error"); return; } LNode *p = head; LNode *tmp; int i = 1; while (i != pos) { p = p->next; i++; } tmp = p->next; p->next = tmp->next; free(tmp); } void List_Reverse(LNode* head)//鏈表轉置 { if (EmptyList(head))return; LNode *p1, *p2, *p3; p1 = head->next; p2 = p1->next; p3 = p2->next; head->next = NULL; p1->next = NULL; while (p3->next) { p2->next = p1; p1 = p2; p2 = p3; p3 = p2->next; } p2->next = p1; p3->next = p2; head->next = p3; } void Clear_List(LNode* head)//鏈表清空 { LNode *p,*tmp; p = head->next; while (p) { tmp = p; p = p->next; free(tmp); } head->next = NULL; } int Find_Node(LNode* head,ElemType data)//鏈表根據查找的元素查詢位置 { if (EmptyList(head))return NULL; int pos=1; LNode *p = head->next; while (p) { if(p->data==data) { return pos; } p = p->next; pos++; } } void main() { LNode *L = create_head(); Insert_byHead(L, 5); Insert_byHead(L, 7); Insert_byHead(L, 9); Insert_byHead(L, 6); Insert_byHead(L, 4); // Insert_Node(L, 5, 1); // Delete_Node(L, 6); List_Reverse(L); // Clear_List(L); Print_List(L); cout<<Find_Node(L,4); system("pause"); }

帶頭結點的單鏈表操作(頭插法)-c++