链表之Python与C

32 阅读1分钟

C

typedef struct STU
{
	int score;
	struct STU* next;
}student;

student* creat(int n)
{
	student* head, * node, * end;
	head = (student*)malloc(sizeof(student));
	end = head;
	for (int i = 0; i < n; i++)
	{
		node = (student*)malloc(sizeof(student));
		node->score = i + 1;
		end->next = node;
		end = node;
	}
	end->next = NULL;
	return head;
}

student* search(student* stu, int n)
{
	for (int i = 0; i < n; i++)
	{
		if (stu->next)
		{
			stu = stu->next;
			printf("%d  ", stu->score);
		}
		else
		{
			return NULL;
		}
	}
	printf("\r\n");
	return stu;
}
void delet(student* stu, int n)
{
	student* last = NULL;
	for (int i = 0; i < n; i++)
	{
		if (stu->next)
		{
			last = stu;
			stu = stu->next;
		}
	}
	if (stu)
	{
		last->next = stu->next;
		free(stu);
	}
}

void insert(student* stu, int n)
{
	for (int i = 0; i < n; i++)
	{
		if (stu->next)
		{
			stu = stu->next;
		}
	}
	if (stu)
	{
		student* node = (student*)malloc(sizeof(student));
		node->next = stu->next;
		stu->next = node;
		node->score = 0;
	}

}

Python

class Node:
    def __init__(self, data, pnext=None):
        self.data = data
        self.next = pnext
    def val(self):
        return self.data
class List:
    def __init__(self):
        self.phead = None
        self.length = 0
    def isempty(self):
        return self.length == 0
    def create(self, data):
        self.phead = Node(None)
        pend = self.phead
        for i in data:
            node = Node(i)
            pend.next = node
            pend = node
            self.length += 1
        pend.next = None
    def display(self):
        curson = self.phead.next
        for i in range(self.length):
            print(curson.val())
            curson = curson.next