C++创建一个至少包含五个结点的单链表,将单项列表逆置
2个回答
展开全部
单链表的逆序, 真的好绕啊,,,,绕晕了 。。。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
我来写个,用了点淫技 : )
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode * next;
ListNode(int x, ListNode * next=NULL):val(x), next(next) {}
};
void printList(ListNode * pHead) {
for(; pHead!=NULL; pHead=pHead->next) {
cout << pHead->val << "->";
}
cout << "*" << endl;
}
ListNode * reverseList(ListNode * pHead) {
ListNode * pre = NULL;
while(pHead!=NULL) {
ListNode * next = pHead->next;
pHead->next = pre;
pre = pHead;
pHead = next;
}
return pre;
}
void main1() {
// 我一般不会教别人这种淫技: 不需要new也能创建链表!
ListNode nodes[] = {1,2,3,4,5,6,7,8,9};
int n = sizeof(nodes) / sizeof(nodes[0]);
for(int i=0; i<n-1; i++) {
nodes[i].next = &nodes[i+1];
}
ListNode * pHead = nodes;
printList(pHead);
pHead = reverseList(pHead);
printList(pHead);
}
ListNode * appendNode(ListNode * pTail, int value) {
pTail->next = new ListNode(value);
return pTail->next;
}
void main2() {
//好吧还是给个正常点的:
ListNode * pHead = new ListNode(1);
ListNode * pTail = appendNode(pHead, 2);
pTail = appendNode(pTail, 3);
pTail = appendNode(pTail, 4);
pTail = appendNode(pTail, 5);
pTail = appendNode(pTail, 6);
pTail = appendNode(pTail, 7);
pTail = appendNode(pTail, 8);
pTail = appendNode(pTail, 9);
printList(pHead);
pHead = reverseList(pHead);
printList(pHead);
while(pHead != NULL) {
ListNode * pToDelete = pHead;
pHead = pHead->next;
delete pToDelete;
}
}
int main() {
main1();
main2();
return 0;
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询