1. 程式人生 > 其它 >線性表(鏈式儲存結構)

線性表(鏈式儲存結構)

鏈式與順序結構的最大區別在於,插入或刪除操作需要移動大量元素。

連結串列型別:單鏈表,迴圈連結串列,雙向連結串列。

單鏈表的組成:每個資料元素內包括兩個域:資料域和指標域。

單鏈表的建立方式有兩種:一種是頭插法和尾插法。

#include <stdio.h>
#include <stdlib.h>

typedef int ElemType;

typedef struct Node{
    ElemType data;
    struct Node *next;
}ListNode;

typedef ListNode *LinkList; 

/**
***插入 
**
*/ void InsertList(LinkList head, int i, ElemType x) { ListNode *p, *s; int j = 0; p = head; while(p != NULL && j < i - 1) { p = p->next; ++j; } if (p == NULL) { printf("ERROR\n"); return ; } else { s = (ListNode *)malloc
(sizeof(ListNode)); s->data = x; s->next = p->next; p->next = s; } } /** *** 刪除 **/ ElemType DeleteList(LinkList head, int i) { ListNode *p, *s; ElemType x; int j = 0; p = head; while (p != NULL && j < i - 1) { p = p->next; ++j; }
if (p == NULL) { printf("position error\n"); return -1; } else { s = p->next; p->next = s->next; x = s->data; free(s); return x; } } /** **頭插法 **/ LinkList CreateListHead() { LinkList head = NULL; ListNode *p; int ch; while( (ch = getchar() )!= '\n') { p = (ListNode *)malloc(sizeof(ListNode)); p->data = ch; p->next = head; head = p; } return head; } /** ** 尾插法 **/ LinkList CreateListTail() { LinkList head = (ListNode *)malloc(sizeof(ListNode)); ListNode *p, *r; int ch; r = head; while( (ch = getchar()) != '\n') { p = (ListNode *)malloc(sizeof(ListNode)); p->data = ch; r->next = p; r = p; } r->next = NULL; return head; } ListNode *LocateNodek(LinkList head, ElemType k) { ListNode *p = head->next; while(p && p->data != k) { p = p->next; } return p; } ListNode *GetNodei(LinkList head, int i) { ListNode *p; int j = 1; p = head->next; while( p!= NULL && j < i) { p = p->next; ++j; } if (j == i) return p; else return NULL; }