首页 > 试题广场 >

Reversing Linked List (25)

[编程题]Reversing Linked List (25)
  • 热度指数:2826 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For
example, given L being 1→2→3→4→5→6, if K = 3, then you must output 3→2→1→6→5→4; if K = 4, you must output
4→3→2→1→5→6.

输入描述:
Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N 
(<= 105) which is the total number of nodes, and a positive K (<=N) which is the length of the sublist to be reversed.
The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.


输出描述:
For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.
示例1

输入

00100 6 4<br/>00000 4 99999<br/>00100 1 12309<br/>68237 6 -1<br/>33218 3 00000<br/>99999 5 68237<br/>12309 2 33218

输出

00000 4 33218<br/>33218 3 12309<br/>12309 2 00100<br/>00100 1 99999<br/>99999 5 68237<br/>68237 6 -1

注意!!!!!注意!!!!!!!!!!有个大坑,此类题常有出现!!!!就是列表长度不是N!!!!不是N!!!!虽然有有N个Node但他们不一定连续哦
发表于 2017-08-01 10:23:38 回复(2)
//方法1:用数组模拟
#include <iostream>
#include <algorithm>
using namespace std;
#define maxn 100010
int main() {
    int first, k, n, adress,count=0;
    cin >> first >> n >> k;
    int data[maxn], next[maxn], order[maxn];
    for (int i = 0; i < n; i++) {
        cin >> adress;
        cin >> data[adress] >> next[adress];
    }
    while (first != -1) {
        order[count++] = first;
        first = next[first];
    }
    n=count;
    for (int i = 0; i < (n - n % k); i += k)
        reverse(order + i, order + i + k);
    for (int i = 0; i < n - 1; i++)
        printf("%05d %d %05d\n", order[i], data[order[i]], order[i + 1]);
    printf("%05d %d -1", order[n - 1], data[order[n - 1]]);
    return 0;
}


//方法2:用双链表过的了PAT过不了牛客所有数据
#include <iostream>
#include <string>
using namespace std;
const int maxn=100010;
struct Node{
 int data,next,pre;
}node[maxn];
int order[maxn];
int main(){
 int n,k,head,group,num,count=0;
 cin>>head>>n>>k;
 for(int i=0;i<n;i++){
  cin>>num;
  cin>>node[num].data;
  cin>>node[num].next;
 }
 node[head].pre=-1;
 num=head;
 for(int i=1;i<=n;i++){
  count++;
  order[i]=num;
  if(node[num].next==-1) break;
  node[node[num].next].pre=num;
  num=node[num].next;
 }
 n=count;
 group=n/k;
 for(int i=1;i<=group;i++){
  num=order[i*k];
  for(int j=1;j<=k;j++){
   printf("%05d %d ",num,node[num].data);
   if(j!=k){
    printf("%05d\n",node[num].pre);
    num=node[num].pre;
   }
   else if(i<group)
    printf("%05d\n",order[(i+1)*k]);
   else if(n%k==0) printf("-1\n");
   else{
    printf("%05d\n",node[order[i*k]].next);
    num=node[order[i*k]].next;
   }
  }
 }
 if(n%k!=0){
  k=n%k;
  for(int j=1;j<=k;j++){
   printf("%05d %d ",num,node[num].data);
   if(j!=k){
    printf("%05d\n",node[num].next);
    num=node[num].next;
   }
   else printf("-1\n");
  }
 }
 return 0;
} 

编辑于 2019-01-05 14:34:33 回复(0)
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
 
struct node{
    intaddress;
    intvalue;
    node(inta, intv){
        address = a;
        value = v;
    }
};
intmain(){
    intfirst, n, k;
    cin >> first >> n >> k;
     
    intnumber[100005][2];
    for(inti = 0; i < n; i++){
        intaddress, data, next;
        cin >> address >> data >> next;
        number[address][0] = data;
        number[address][1] = next;
    }
     
    vector<node> num;
    while(first != -1){
        num.push_back(node(first, number[first][0]));
        first = number[first][1];
         
        if(num.size() % k == 0){
            reverse(num.end()-k, num.end());
        }
    }
     
    for(inti = 0; i < num.size(); i++){
        cout <<setfill('0') << setw(5) << num[i].address << " "<< num[i].value << " ";
        if(i != num.size() - 1){
            cout <<setfill('0') << setw(5) << num[i+ 1].address << endl;
        }else{
            cout << "-1"<< endl;
        }
    }
     
     
     
    return0;
}

发表于 2016-09-23 02:08:06 回复(0)
这个题目主要考查链表反转。但是,我们并没有必要真的去将数据存储在链表中,然后修改指针去反转。我的做法是,将数据按照链存储在vector中,运用c++函数reverse(),根据K的大小将一段数据反转,实现最终效果。
发表于 2015-06-29 22:54:59 回复(1)
看到大家都是用数组模拟的,我的思路可能不太一样,看到反转有两个思路,一个是用前插法来反转,另一个是用栈,入栈序列刚好和出栈序列相反。由于这个题没有头节点,就用栈来做了,每K个元素进栈,在顺序出栈,改变指向就可以。

//#define LOCAL
#include<iostream>
#include<stack>

using namespace std;

const int maxn = 100000 + 5;

struct Node{
    int addr, data, next;
}nodes[maxn];

int N,K;

int main(){
    #ifdef LOCAL
        freopen("C:\\Users\\Riga\\Desktop\\data.in","r",stdin);
    #endif
    int begin;
    scanf("%d %d %d",&begin,&N,&K);
    for(int i=0;i<N;i++){
        int addr,data,next;
        scanf("%d %d %d",&addr,&data,&next);
        nodes[addr] = {addr,data,next};
    }
    int cnt = 0,pre = -1, q;
    stack<int> sn;
    for(int p=begin;p!=-1;){
        cnt++;
        sn.push(p);
        if(cnt==K){
            q = nodes[p].next;
            int tmp = sn.top();
            if(pre!=-1)
                nodes[pre].next = tmp;
            else
                begin = tmp;
            sn.pop();
            while(!sn.empty()){
                int tmpAddr = sn.top();
                nodes[tmp].next = tmpAddr;
                tmp = tmpAddr;
                sn.pop();
            }
            nodes[tmp].next = q;
            pre = nodes[tmp].addr;
            p = q;
            cnt = 0;
        }else{
            p = nodes[p].next;
        }
    }
    for(int p=begin;p!=-1;p=nodes[p].next){
        if(nodes[p].next!=-1)
            printf("%05d %d %05d\n", p, nodes[p].data, nodes[p].next);
        else
            printf("%05d %d %d\n", p, nodes[p].data, nodes[p].next);
    }
    return 0;
}
发表于 2021-01-31 15:45:29 回复(0)
没几个老老实实反转链表的吗?
#include<cstdio>
using namespace std;
class Node{
public:
  int addr;
  int val;
  Node* next;
  Node():next(NULL){}
};
Node nodes[100000];
void printList(Node* head){
    while(head != NULL){
        printf("%05d %d ",head->addr,head->val);
        if(head->next != NULL) printf("%05d\n",head->next->addr);
        else printf("-1\n");
        head = head->next;
    }
}
Node* reverseList(Node* head){
    Node* prev = NULL;
    while(head){
        Node* tmp = head->next;
        head->next = prev;
        prev = head;
        head = tmp;
    }
    return prev;
}
Node* reverseListByK(Node* head,int k){
    if(!head || !head->next) return head;
    int i = 0;
    Node* tmp = head;
    for(; i < k-1 && head; i++){
        head = head->next;
    }
    if(head == NULL){
        return tmp;
    }else{
        Node* nextH = head->next;
        head->next = NULL;
        Node* pre = reverseList(tmp);
        Node* res = reverseListByK(nextH,k);
        tmp->next = res;
        return pre;
    }
}
int main(){
    int hAddr,N,K;
    Node* head = NULL;
    scanf("%d %d %d",&hAddr,&N,&K); 
    for(int i=0 ; i < N; i++){
        int addr,val,naddr;
        scanf("%d %d %d",&addr,&val,&naddr);
        nodes[addr].addr = addr;
        nodes[addr].val = val;
        if(naddr != -1) nodes[addr].next = &nodes[naddr];
        if(addr == hAddr) head = &nodes[addr];
    }
    Node* nhead = reverseListByK(head,K);
    printList(nhead);
    return 0;
}

发表于 2019-01-30 20:33:34 回复(1)
这个题做的很草率,其实还有些小问题,还可以优化,但是过了,没时间了就不细究了。
//开始用map,然后找链表,简单点方法就是存入数组或者向量然后用reverse。
注意输出的时候下一个的地址不能用当前结点的next,这个next是随着输出的时候的值,要用下一个结点的address来输出才对
#include<iostream>
(720)#include<vector>
#include<algorithm>
(831)#include<map>
using namespace std;
const int maxn = 100010;
struct node {
	int address;
	int val;
	int next;
	node(int a,int v, int n): address(a),val(v), next(n) {}
	node():address(-1),val(0),next(-1){}
};
int main() {
	int head, n, k;
	 vector<node>nodes(maxn);
	cin >> head >> n >> k;
	for (int i = 0; i < n; i++) {
		int address, val, next;
		cin >> address >> val >> next;
		nodes[address] = node(address,val, next);
	}
	vector<node>answer;
	int count = 0;
	while (head != -1) {//head用来遍历,结果头结点保留在result中
		answer.push_back(node(head,nodes[head].val,nodes[head].next));
		count++;
		head = nodes[head].next;
		if (count % k == 0) {
			reverse(answer.begin()+count-k,answer.end());
		}
	}
	for(int i=0;i<answer.size()-1;i++){
		printf("%05d %d ", answer[i].address,answer[i].val);
		printf("%05d\n", answer[i + 1].address);
	}
	printf("%05d %d -1\n", answer[answer.size()-1].address, answer[answer.size() - 1].val);
}


发表于 2020-04-01 00:08:33 回复(0)
简单模拟题,直接使用数组来存储一条链,然后按照部分倒转后的规律进行输出即可。
注意一些细节:
1.由于下一个节点的起点和当前节点的地址相同,所以输出当前节点的next值可以交给下一个节点来完成。
2.给出的节点不一定全部会被用到,处理不好可能会造成数组越界访问。
#pragma warning(disable : 4996)
(1164)#include<stdio.h>
#include<iostream>
(720)#include<vector>
#include<algorithm>
using namespace std;
(1165)#define MAXIMUN 100001
struct Node{
	int adr;
	int data;
	int next;
};

Node temp[MAXIMUN];

int origin, member, group;

int main(){
	//获取输入,保存节点
	cin >> origin >> member >> group;
	for (int i = 0; i < member; i++){
		int tmpAdr;
		scanf("%d", &tmpAdr);
		scanf(" %d %d", &temp[tmpAdr].data, &temp[tmpAdr].next);
		temp[tmpAdr].adr = tmpAdr;
	}
	//根据节点的地址整理成一条链
	vector<Node> nodes;
	int nowAt = origin;
	while (nowAt != -1) {
		nodes.push_back(temp[nowAt]);
		nowAt = temp[nowAt].next;
	}
	//输出答案
	member = nodes.size();
	int groupNum=member/group, remain=member%group;	//完整组的数量以及残余的节点
	if (group <= 1) {
		groupNum = 0;
		remain = member;
	}
	bool firstOutPut = true;
	for (int i = 0; i < groupNum; i++){
		int first = i*group;
		int last = first + group - 1;
		for (int j = last; j >= first; j--){
			if (firstOutPut) {
				firstOutPut = false;
				printf("%05d %d", nodes[j].adr, nodes[j].data);
			}
			else{
				printf(" %05d\n%05d %d", nodes[j].adr, nodes[j].adr, nodes[j].data);
			}
		}
	}
	for (int i = member - remain; i < member; i++){
		if (firstOutPut) {
			firstOutPut = false;
			printf("%05d %d", nodes[i].adr, nodes[i].data);
		}
		else{
			printf(" %05d\n%05d %d", nodes[i].adr, nodes[i].adr, nodes[i].data);
		}
	}
	cout << " -1" << endl;
	return 0;
}


发表于 2020-03-01 13:02:49 回复(0)
#include<cstdio>
(802)#include<iostream>
using namespace std;

struct node {
	int addr;
	int data;
	node* next;
};
typedef node* List;
node lists[100007];

void reverse(List head, int k, int n)
{
	List new_head, old_head, temp;
	List succ, prev;
	List p = head;
	prev = p;

	int i;
	for (i = 1; i <= n && p; i++)
	{
		p = p->next;

		if (i % k == 0)
		{
			old_head = prev->next;
			new_head = NULL;
			succ = p->next;
			
			while (old_head != succ)
			{
				temp = old_head;
				old_head = old_head->next;
				temp->next = new_head;
				new_head = temp;
			}

			p = prev;
			while (p->next)
				p = p->next;

			p->next = succ;
			prev->next = new_head;

			prev = p;
		}
	}
}

void print(List head)
{
	List p = head->next;
	while (p)
	{
		if(p->next)
			printf("%05d %d %05d\n", p->addr, p->data, p->next->addr);
		else
			printf("%05d %d -1", p->addr, p->data);
		p = p->next;
	}
}

void freeList(List list)
{
	List p = list, temp;
	while (p)
	{
		temp = p;
		p = p->next;
		free(temp);
	}
}

int main()
{
	int n, k, faddr;
	List head = new node;
	ios::sync_with_stdio(false);
	cin >> faddr >> n >> k;
	for(int i = 0; i < n; i++)
	{
		int addr, data, naddr;
		cin >> addr >> data >> naddr;
		lists[addr].addr = addr;
		lists[addr].data = data;
		if(naddr != -1) 
			lists[addr].next = &lists[naddr];
		if(addr = faddr)
			head->next = &lists[addr];
	}
	reverse(head, k, n);
	print(head);
    delete head;
	//freeList(head);
}
老老实实建链表PAT能过这过不了,用这种建链表方式这能过PAT过不了= =
发表于 2020-02-22 21:01:45 回复(0)
#define _CRT_SECURE_NO_WARNINGS
#
include <iostream>
#include <algorithm>
#
include <cmath>
#include <string>
#
include <set>
#include <vector>
#
include <map>
#include <iomanip>
#
include <sstream>
using namespace std;

//1074 Reversing Linked List
//地址是个5位非0数字,所以可以直接用大数组去覆盖。
//看了柳神博客才知道,不是所有结点都有用。
//所以总的有效结点数并非n,需要自己用一个cnt来统计,pat.6考察这点。

int val[100000], nxt[100000];
int lis[1000000]; //用来存地址序列,以地址作为主键
int res[1000000]; //存排序后的地址序列

int main() {
    int head, n, k;
    cin >> head >> n >> k;
    int ad, v, nx;
    for (int i = 0; i < n; ++i) {
        scanf("%d%d%d",&ad,&v,&nx); //坑爹,用cin就卡pat.5超时
        val[ad] = v;
        nxt[ad] = nx;
    }

    //建立lis
    int p = head,idx=0;
    while (p != -1) {
        lis[idx++] = p;
        p = nxt[p];
    }
    int cnt = idx; //这是总的有效结点数

    //排序,看样例多余的不满k个的余项是不必倒排的
    int seg = cnt / k; //地板除
    idx = 0;
    for (int i = 0; i < seg; ++i) {
        //逆转lis[i*k,(i+1)*k)区间内的地址
        for (int j = (i + 1)*k - 1; j >= i * k; --j) {
            res[idx++] = lis[j];
        }
    }
    //处理余项
    for (int j = seg * k; j < cnt; ++j) {
        res[idx++] = lis[j];
    }

    //输出结果
    for (int i = 0; i < cnt -1; ++i) {
        cout << setfill('0') << setw(5) << res[i] << " " << val[res[i]] << " " << setw(5) << res[i + 1] << endl;
    }
    cout << setfill('0') << setw(5) << res[cnt - 1] << " " << val[res[cnt - 1]] << " " << -1;

    return 0;
}
发表于 2020-02-22 15:23:33 回复(0)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct node{
	int ad,d,next;
}no[100000];
int main(){
	int h,n,k;
	cin>>h>>n>>k;
	for(int i=0;i<n;i++){
		int t;cin>>t;no[t].ad=t;
		cin>>no[t].d>>no[t].next;
	}
	vector<node> r;
	for(int cur=h;cur!=-1;cur=no[cur].next){
		r.push_back(no[cur]);
	}
	for(int i=0;i<r.size()/k;i++){
		auto it=r.begin()+i*k;
		reverse(it,it+k);
	}
	for(int i=0;i<r.size();i++){
		printf("%05d %d ",r[i].ad,r[i].d);
		if(i==r.size()-1) cout<<"-1"<<endl;
		else printf("%05d\n",r[i+1].ad);
	}
	return 0;
}


编辑于 2020-01-14 16:28:27 回复(0)
tem = list(map(str,input().split()))
start,n,k  = tem[0],int(tem[1]),int(tem[2])
lst,lst1 = [None,None]*100001,[]
for i in range(0,n):
    a,b,c = map(str,input().split())
    lst[int(a)] = [b,c]
tem = []
while start!='-1': 
   tem.append([start,lst[int(start)][0]])
   start = lst[int(start)][1]
   if len(tem)==k:
       lst1.extend(tem[::-1])
       tem = []
lst1.extend(tem)
for i in range(0,len(lst1)-1):
    print(lst1[i][0]+" "+lst1[i][1]+" "+lst1[i+1][0])
print(lst1[len(lst1)-1][0]+" "+lst1[len(lst1)-1][1]+" "+"-1") 
要注意的是。。。测试案例有10**5的数据量,所以不能有多余的循环
编辑于 2018-12-05 17:21:07 回复(0)
start,N,K=map(int,input().split())
L=[None,None]*100005
for i in range(N):
    a,b,c=map(int,input().split())
    L[a]=[b,c]
res,tmp=[],[]
while start!=-1:
    tmp.append([start,L[start][0]])
    start=L[start][1]
    if len(tmp)==K:
        res.extend(tmp[::-1])
        tmp=[]
else:
    res.extend(tmp)
for i in range(len(res)-1):
    print('{:05d} {} {:05d}'.format(res[i][0],res[i][1],res[i+1][0]))
print('{:05d} {} {}'.format(res[-1][0],res[-1][1],-1))

发表于 2018-09-06 14:48:18 回复(1)

测试用例全部通过,内存用得多了。

#include<cstdio>
#include<stack>
#include<iostream>
using namespace std;
struct Node {
    int now;
    int data;
    int next;
}node[1000010],tp[1000010],prt[1000010],t;
int main() {
    int fstad, K, N;
    scanf("%d%d%d", &fstad, &N, &K);
    int temp;
    for (int i = 0; i < N; i++) {
        scanf("%d", &temp);
        node[temp].now = temp;
        scanf("%d%d",&node[temp].data, &node[temp].next);
    }
    t = node[fstad];
    int cnt = 1;
    tp[0] = t;
    while (t.next!= -1) {
        tp[cnt++] = node[t.next];
        t = node[t.next];
    }
    int length = cnt;
    stack<Node> st;
    cnt = 0;
    for (int i = 0; i+K <=length; i+=K) {
        for (int j = i; j < i + K; j++) {
            st.push(tp[j]);
        }
        while (!st.empty()) {
            prt[cnt++] = st.top();
            st.pop();
        }
    }
    for (int i = cnt; i < length; i++) {
        prt[i] = tp[i];
    }
    for (int i = 0; i < length-1; i++) {
        prt[i].next = prt[i + 1].now;
    }
    prt[length- 1].next = -1;
    for (int i = 0; i <length; i++) {
        if(i<length-1)
            printf("%05d %d %05d\n", prt[i].now, prt[i].data, prt[i].next);
        else
            printf("%05d %d %d", prt[i].now, prt[i].data, prt[i].next);
    }
}
发表于 2018-01-29 18:57:24 回复(0)
import java.util.HashMap;
import java.util.Scanner;

public class Main8 {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String headAddress = in.next();
		int N = in.nextInt();
		int K = in.nextInt();
		HashMap<String, Node> map = new HashMap<>();
		for (int i = 0; i < N; i++) {
			String address = in.next();
			int val = in.nextInt();
			String nextAddress = in.next();
			Node node = map.get(address);
			if (node == null) {
				node = new Node();
				node.address = address;
				node.val = val;
				Node next = map.get(nextAddress);
				if (next == null) {
					next = new Node();
					next.address = nextAddress;
				}
				node.next = next;
				map.put(address, node);
				map.put(nextAddress, next);
			} else {
				node.val = val;
				Node next = map.get(nextAddress);
				if (next == null) {
					next = new Node();
					next.address = nextAddress;
				}
				node.next = next;
				map.put(address, node);
				map.put(nextAddress, next);
			}
		}
		Node head = map.get(headAddress);
		map.clear();
		head = reverseKGroup(head, K);
		while (head != null && !head.address.equals("-1")) {
			System.out.println(head.address + " " + head.val + " " + head.next.address);
			head = head.next;
		}

	}

	public static Node reverseKGroup(Node head, int k) {
		Node cur = head;
		int count = 0;
		while (cur != null && !cur.address.equals("-1") && count != k) {
			cur = cur.next;
			count++;
		}
		if (count == k) {
			cur = reverseKGroup(cur, k);
			while (count-- > 0) {
				Node tmp = head.next;
				head.next = cur;
				cur = head;
				head = tmp;
			}
			head = cur;
		}
		return head;
	}
}

class Node {
	int val;
	String address;
	Node next;
}
为什么内存会爆
发表于 2017-09-06 10:55:18 回复(0)
public class Main {
 	    public static final int MAX=100000;
    public Node[] list;
    public int headAddress,rhead;
    public int N,K;
    public class Node{
        int data=0;
        int next=0;
        int address=0;
        public Node(int address,int data,int next){
            this.address=address;
            this.data=data;
            this.next=next;
        }
    }


    public void createPoly(){
        int nodeAddress,i=0;
        int data,next;
        Scanner s=new Scanner(System.in);
        headAddress=s.nextInt();
        N=s.nextInt();
        K=s.nextInt();

        if(headAddress<0||headAddress>99999||N>100000||N<0||K<0)
        {
            System.out.println("Input Error");
            return;
        }
        //variable can be declared but not initilize,
        //here we initialize the list!
        list=new Node[MAX];
        while(i<N){
            //Actually,it is not needed to use getLine.
           String str=s.nextLine();
            String[] arr=str.split(" ");
            int[] arrx=new int[arr.length];
            for(int k=0;k<arr.length;k++){
                 arrx[k]=Integer.parseInt(arr[k]);
            }
            nodeAddress=s.nextInt();
            data=s.nextInt();
            next=s.nextInt();
            list[nodeAddress]=new Node(nodeAddress,data,next);

            i++;
        }
    }

    public void printList(Node[] xlist,int xheadAddress){
        while(xlist[xheadAddress].next!=-1){
            System.out.printf("%05d %d %05d\n",xheadAddress,xlist[xheadAddress].data,xlist[xheadAddress].next);
            xheadAddress=xlist[xheadAddress].next;
        }
        System.out.printf("%05d %d %05d\n",xheadAddress,xlist[xheadAddress].data,xlist[xheadAddress].next);

    }

    public Node[] reverse(){
        //list
        Stack<Node> s1=new Stack<Node>();
        Node[] rlist=new Node[MAX];
        int rheadAddress=0,rear=0,Last=0;
        if(N<K)
            return null;
        int count=N/K;

        while(count>0){
            for(int i=0;i<K;i++){
                s1.push(list[headAddress]);
                rheadAddress=headAddress;
                headAddress=list[headAddress].next;
            }
            if(count==N/K)
            {
                rhead=s1.peek().address;
            }
            count--;
            for(int j=0;j<K;j++){
                //if N%K==0 , it will pop
                if(!s1.empty()){
                    //这里花费了一晚上,对于内存管理的不了解!
                    Node xtmp=s1.pop();
                    Node tmp=new Node(xtmp.address,xtmp.data,xtmp.next);
                    rlist[rheadAddress]=tmp;
                    if(count==0&&j==0){
                        Last=tmp.address;
                    }
                    //using top()!!!!!!!
                    if(s1.empty()){
                        if(count==0)
                            rear=tmp.address;
                        break;
                    }
                    rlist[rheadAddress].next=s1.peek().address;
                    rheadAddress=rlist[rheadAddress].next;
                }
            }
        }
        System.out.printf("%d %d\n",Last,rear);
        if(N%K!=0){
            int num=N%K+1;//Start from the node "1", the node rear.
            //So including rear there shall add 1.
            while(num>0){
                Node tmp=new Node(rear,list[rear].data,list[Last].next);
                rlist[rear]=tmp;
                //rlist[rear].next=list[Last].next;
                Last=list[Last].next;
                rear=Last;
                num--;
            }

        }
        return rlist;

    }

    public static void main(String[] args) {
     	Main r=new Main();
        Scanner s=new Scanner(System.in);
      /*  int[] arrx=new int[4];
        String str=s.nextLine();
        String[] arr=str.split(" ");
        for(int i=0;i<arr.length;i++){
            arrx[i]=Integer.parseInt(arr[i]);
        }
        System.out.println(arrx[0]);
        System.out.println(arrx[1]);
*/
        Node[] rlist;
        r.createPoly();
        r.printList(r.list,r.headAddress);
        rlist=r.reverse();

        System.out.println(rlist[r.rhead].data);
        int rhead=r.rhead;
       r.printList(rlist,rhead);
    }
   
}

编辑于 2016-09-07 17:56:27 回复(0)
这道题的亮点在于不是使用真正的链表,而是用数组去模拟!
发表于 2016-08-15 11:00:44 回复(1)
啥头像
楼上说得没错,题目给的不是真正的链表,可以按照给的结构来反转

#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>

using namespace std;

struct Node
{
    int address, val;
    Node(int _address, int _val) {
        address = _address;
        val = _val;
    }
    Node() {}
};

int data[100000][2];

int main()
{
    // 读入数据
    int startAdress, N, K; scanf("%d %d %d", &startAdress, &N, &K);
    int address, val, next;
    while(N--) {
        scanf("%d %d %d", &address, &val, &next);
        data[address][0] = val;
        data[address][1] = next;
    }
    vector<Node> rlt; address = startAdress; int idx1=0, idx2=0;
    while(address != -1) {
        rlt.push_back(Node(address, data[address][0]));
        address = data[address][1];
        idx2++;
        if(idx2%K == 0) {
            reverse(rlt.begin()+idx1, rlt.begin()+idx2);
            idx1 = idx2;
        }
    }
    for(int i=0; i<idx2-1; i++) {
        printf("%05d %d %05d\n", rlt[i].address, rlt[i].val, rlt[i+1].address);
    }
    printf("%05d %d -1\n", rlt[idx2-1].address, rlt[idx2-1].val);
    return 0;

} 


发表于 2015-12-27 09:41:39 回复(0)