Single LinkedList Exercise
#include <stdio.h>
struct stu {
int num;
struct stu*next;
}; // 자기참조 구조체
void main()
{
struct stu*head; // 첫번째 노드를 가르키는 포인터
struct stu*cur; // 잡일(검색,출력 ect..)
struct stu*del; // 정적메모리로 할당 시 사용하지 않음
struct stu*new1; // 정적메모리로 할당 시 사용하지 않음
struct stu aa, bb, cc; // 정적메모리로 할당
aa.num = 1;
bb.num = 2;
cc.num = 3;
// 연결
cur = head = &aa;
cur->next = &bb;
cur->next->next = &cc;
cur->next->next->next = NULL;
cur = head; // cur를 다시 aa위치로
/*
cur = &aa;
head = &aa;
cur->next = &bb;
cur = cur->next; // cur위치 이동
cur->next = &cc;
cur = cur->next;
cur->next = NULL;
cur = head;
*/
while (cur != NULL) {
printf("%d\n", cur->num);
cur = cur->next; // cur 위치 이동
}
}
dynamic binding in LinkedList
#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable:4996)
struct A {
int num;
struct A*next;
};
void main() {
int o, i;
struct A*head = NULL;
struct A*cur = NULL;
struct A*del = NULL;
struct A*new1 = NULL;
head = cur = new1 = (struct A*)malloc(sizeof(struct A));
new1->num = 1;
new1->next = NULL;
new1 = (struct A*)malloc(sizeof(struct A));
new1->num = 2;
new1->next = NULL;
cur->next = new1;
new1 = (struct A*)malloc(sizeof(struct A));
new1->num = 3;
new1->next = NULL;
cur->next->next = new1;
cur = head;
while (cur != NULL) {
printf("%d", cur->num);
cur = cur->next;
}
//삽입
new1 = (struct A*)malloc(sizeof(struct A));
new1->num = 4;
new1->next = NULL;
printf("몇번째에 삽입할까요?");
scanf("%d", &o);
cur = head;
if (o == 1) { // 노드 검색
new1->next = head;
head = new1;
}
else {
cur = head;
for (i = 0 ; i < o - 2 ; i++) { // cur의 위치
cur = cur->next; / / 다음 노드로 이동시키기
/*
while(c-2>0){
cur=cur->next;
c--;
}
*/
}
new1->next = cur->next; // 뒷부분연결
cur->next = new1; //앞부분 연결
}
cur = head;
while (cur != NULL) {
printf("%d", cur->num);
cur = cur->next;
}
//삭제
printf("몇번을 삭제할까요?");
scanf("%d", &o);
cur = head;
if (o == 1) { // 삭제노드 검색
del = head; // 삭제노드 연결
head = head->next; // 연결
del->next = NULL; //끊기
free(del); //del이 가르키고 있는 동적메모리 해제
}
else {
cur = head;
for (i = 0 ; i < o - 2 ; i++)
{
cur = cur->next;
}
del = cur->next; // 삭제노드연결
cur->next = del->next; // 연결
del->next = NULL; //끊기
free(del);
}
cur = head;
while (cur != NULL) {
printf("%d", cur->num);
cur = cur->next;
}
//전체 삭제
cur = head;
while (cur != NULL) {
del = cur;
cur = cur->next;
del->next = NULL;
free(del);
}
if (cur == NULL)puts("all delete");
}