C++数据结构-单链表

这里是 单链表模块化代码


  • 建立一个节点类型
struct Node {
    int data;//节点的内容
    Node* next;//指向下一节点的指针
};
  • 创建一个简单的单链表
ListNode* createList() {
    int x;
    Node head; 
    Node* p = &head;//这里建立一个可以灵活使用的指针
	head.next = NULL;
    while (cin >> x) {
        p->next= new ListNode;
        p=p->next;
        p->next=NULL;
        p->val=x;
    }
    return head.next;
}
  • 头结点输出单链表
void display(ListNode* p) {
    while (p)
    {
        printf("%d -> ", p->val); 
        p = p->next;
    }
    printf("nullptr\n");
}

int main()
{
    ListNode* L1 = createList();//单链表的创建
	display(L1);//单链表的输出
    ListNode* L2 = reverseList(L1);//单链表的原地翻转
    return 0;
}
  • 进行原链表的原地翻转
ListNode* reverseList(Node* head) {
	if (head == NULL) return NULL;
    Node* p=head->next;
    head->next=NULL;
    while (p){
    	Node* q=p->next;
    	p->next=head;
    	head=p;
    	p=q;
	}
	return head;
}

约瑟夫问题
问题即,1,2,...,n 这 n 个数字排成一个圆圈,从数字1开始,每次从这个圆圈里删除第m个数字。求出这个圆圈里剩下的最后一个数字。

#include <iostream>

using namespace std;

struct Node
{
    int data;
    Node* next;
};

Node* pt;
  • 这里选择创建一个循环的单链表
Node* createList(int n)
{
    Node head;
    Node* p=&head;
    head.next=NULL;
    for (int i=0;i<n;i++){
    	p->next=new Node;
    	p=p->next;
    	p->data=i+1;
    	p->next=NULL;
	}
	pt=p;
	p->next=head.next;
	return head.next;
}
  • 对节点进行删除操作
int remove(Node* head, int m, int n)
{
	int count=0;
	Node* t=head;
    while (t!=pt){
    	count++;
    	if (count==m){
    		t=t->next;
    		delete pt->next;
    		pt->next=t;
    		count=0;
		}
		else {
			pt=t;
			t=t->next;
		}
	}
	return t->data;
}
  • 最后是一段主函数
int main()
{
    int n, m;
    cin >> n >> m;
    Node* L1 = createList(n);
    cout << remove(L1, m, n) << endl;
    return 0;
}
posted @ 2024-10-28 17:41  槭枫  阅读(41)  评论(0)    收藏  举报