1. 程式人生 > 其它 >06. C Pro 連結串列的幾個簡單用例

06. C Pro 連結串列的幾個簡單用例

// 三、判斷一個連結串列是否存在環
/* 兩個指標:slow.step=1, fast.step=2,在環中兩個指標必定相遇 */
typedef struct node {
int elem;
struct node *next;
}Node, *NodeList;

bool IsExitsLoop(NodeList head) {
NodeList slow = head, fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
break;
}
return !(fast == NULL || fast->next == NULL);
}

int main(void) {
//建立一個有環的連結串列
NodeList head = NULL, p, q;
for (int i = 1; i <= 5; i++) {
p = (NodeList)malloc(sizeof(Node));
p->elem = i;
if (head == NULL)
head = q= p;
else
q->next = p;
q = p;
}
p= (NodeList)malloc(sizeof(Node));
p->elem = 6;
q->next = p;
q = p;
q->next = head->next->next->next;
printf("判斷該連結串列是否存在環:");
bool b = IsExitsLoop(head);
printf("%s\n", b == false ? "false" : "true");

getchar(); return 0;
}


// 四、連結串列的逆置
typedef struct node {
int data;
struct node *next;
}Node;

Node *createList(void) {
Node *head, *p, *q;
head = NULL;
p = head;

for (int i = 1; i <= 5; i++) {
p = (Node *)malloc(sizeof(Node));
p->data = i;
if (head == NULL)
head = q = p;
else
q->next = p;
q = p;
}
q->next = NULL;
return head;
}

Node *ReverseList(Node * head) {
Node *p, *q, *r;
p = head;
q = r = NULL;
while (p) {
q = p->next; //p=head,so q 表示 head++
p->next = r; //r 是一個獨立的連結串列R的頭指標,初始化為NULL
r = p; //將 p 壓入連結串列R的表頭
p = q; //head之後的節點組前移,成為新的表頭 p
}
return r;
}

void ShowList(Node *head) {
while (head) {
printf("%d\t", head->data);
head = head->next;
}
printf("\n");
}

int main(void) {
Node *head;
head = createList();
head = ReverseList(head); //Reverse之後,head已經更新
ShowList(head);
getchar(); return 0;
}


//五、連結串列實現:每3去1遊戲
typedef struct Node {
int pos;
struct Node *next;
};
int LENGTH;
Node *createList(void) {
Node *head, *p, *q;
head = NULL;
p = head;

for (int i = 1; i <= LENGTH; i++) {
p = (Node *)malloc(sizeof(Node));
p->pos = i;
if (head == NULL)
head = q = p;
else
q->next = p;
q = p;
}
p->next = head;
return head;
}

int LastOne(Node* head, int len) {
int k = 1;
while (len > 1) {
if (k == 2) {
k = 0;
len--;
head->next = head->next->next;
}
else {
k++;
head = head->next;
}
}
return head->pos;
}

int main(void) {
Node *head;
scanf("%d", &LENGTH);
head = createList();
printf("%d\n", LastOne(head, LENGTH));
getchar(); return 0;
}