链表的反转与旋转

来源:互联网 发布:淘宝网卖辣条怎么样 编辑:程序博客网 时间:2024/05/21 22:20
// ReverseList.cpp: 定义控制台应用程序的入口点。//#include "stdafx.h"#include<iostream>#include<cassert>#include<string>using namespace std;//template <typename T>struct linkList {int val;linkList *next;linkList(int x) {val = x;next = NULL;}};//template <typename T>linkList* creatList(int arr[],int n) {//创建单链表assert(n > 0);linkList *head = new linkList(arr[0]);linkList *cur = head;int i = 1;while (i<n) {cur->next = new linkList(arr[i]);cur = cur->next;i++;}return head;}linkList* ReverseList(linkList *head) {/*if (head == NULL || head->next == NULL)return head;linkList *cur, *pnext, *pre;cur = head->next;pnext = cur->next;cur->next = NULL;while (pnext) {pre = pnext->next;pnext->next = cur;cur = pnext;pnext = pre;}head->next = cur;return head;*///如果有虚拟头结点可以这样反转
linkList *pre, *cur, *pnext;pre = NULL;cur = head;while (cur) {pnext = cur->next;cur->next = pre;pre = cur;cur = pnext;}return pre;}linkList* RotationList(linkList* head,int k){assert(k >= 0);if (k == 0||k==5)return head;//找到倒数第K-1个元素,连接成环,在第K-1和K的中间断开//未考虑链表的长度小于k,如果考虑的话,可以求得链表的长度,大于k然后取余linkList *cur = head,*left=head;int  gt;for (gt = 0; cur->next!=NULL&> < k; gt++)cur = cur->next;while (cur->next) {cur = cur->next;left = left->next;}cur->next = head;head = left->next;left->next = NULL;return head;}void printList(linkList* p) {linkList *cur = p;while (cur!=NULL) {cout << cur->val << "->";cur = cur->next;}cout << "NULL";}
//测试int main(){int a[5] = { 1,2,3,4,5 };linkList *p=creatList(a, 5);cout << "链表反转前:" << endl;printList(p);cout << endl;cout << "链表反转后:" << endl;printList(ReverseList(p));cout << endl;int k = 3;cout << "链表旋转" << k << "次前:" << endl;linkList *q = creatList(a, 5);printList(q);cout << endl;cout << "链表旋转"<<k<<"次后:" << endl;printList(RotationList(q,k));system("pause");    return 0;}

原创粉丝点击