c、c++中一些经典的程序总结

版权声明:本文为博主原创文章,转载请注明此文链接,谢谢了。个人技术博客:https://wardseptember.github.io/ https://blog.csdn.net/wardseptember/article/details/83450950

1.将一单链表逆序(完全正确版)

网上看了很多单链表逆序的代码,多多少少都有一点问题。所以自己写一个。

#include<stdio.h>
#include<malloc.h>
typedef struct LNode 
{
	int data;
	struct LNode *next;
}LNode,*List;
void createListR(LNode *&p, int *a, int n) 
{//尾插法构造单链表
	LNode *s, *r;
	int i;
	r = p;
	for (i = 0; i < n; ++i) 
	{
		s = (LNode*)malloc(sizeof(LNode));
		s->data = a[i];
		r->next = s;
		r = r->next;
	}
	r->next = NULL;
}
List reverseList(List &L)
{
	List currentPos,nextPos,previousPos;
	previousPos=NULL;
	currentPos=L;
	nextPos=L;
	while(nextPos!=NULL)
	{
		nextPos=nextPos->next;
		currentPos->next=previousPos;
		previousPos=currentPos;
		currentPos=nextPos;
	}
	currentPos=previousPos;
	return currentPos;
}
void printList(LNode *p) 
{//输出链表
	if (p->next == NULL)
		printf("链表为空!");
	else 
	{
		while (p != NULL) 
		{
			printf("%d ",p->data);
			p = p->next;
		}
		printf("\n");
	}
}
int main()
{
	int ch[10] = { 15,46,47,29,19,23,68,79,115,784 };
	LNode *p,*q;
	p=(LNode*)malloc(sizeof(LNode));
	q=(LNode*)malloc(sizeof(LNode));
	//带头节点
	createListR(p,ch,10);
	//printList(p->next);
	q=reverseList(p->next);
	printList(q);
	free(q);
	free(p);
	return 0;
}
展开阅读全文

没有更多推荐了,返回首页